Domanda

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

È stato utile?

Soluzione

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?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top