I am quite an average programmer in python and i have not done very complex or any major application with python before ... I was reading new class styles and came across some very new things to me which i am understanding which is data types and classes unification
class defaultdict(dict):
def __init__(self, default=None):
dict.__init__(self)
self.default = default
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.default
but whats really getting me confused is why would they unify them? ... i really can't picture any reason making it of high importance .. i'll be glad if anybody can throw some light on this please Thank you
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 designedUserDictclass, or produce a custom class that provided the fulldictprotocol. Now, you can just doclass 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
dictsubclass that logs modifications to it:Any instance of
LoggingDictcan be used wherever a regulardictis expected:If you instead used a function instead of
LoggingDict:How would you pass
mydicttoadd_value_to_dictand have it log the addition without having to makeadd_value_to_dictknow aboutlog_value?