The primary reason was to allow for built-in types to be subclassed in the same way user-created classes could be. Prior to new-style classes, to create a dict
-like class, you needed to subclass from a specially designed UserDict
class, or produce a custom class that provided the full dict
protocol. Now, you can just do class MySpecialDict(dict):
and override the methods you want to modify.
For the full rundown, see PEP 252 - Making Types Look More Like Classes
For an example, here's a dict
subclass that logs modifications to it:
def log(msg):
...
class LoggingDict(dict):
def __setitem__(self, key, value):
super(LoggingDict, self).__setitem__(key, value)
log('Updated: {}={}'.format(key, value))
Any instance of LoggingDict
can be used wherever a regular dict
is expected:
def add_value_to_dict(d, key, value):
d[key] = value
logging_dict = LoggingDict()
add_value_to_dict(logging_dict, 'testkey', 'testvalue')
If you instead used a function instead of LoggingDict
:
def log_value(d, key, value):
log('Updated: {}={}'.format(key, value))
mydict = dict()
How would you pass mydict
to add_value_to_dict
and have it log the addition without having to make add_value_to_dict
know about log_value
?