How do I properly subclass a "dict"?
class MyDict(dict):
def __init__(self, *args):
#fill in here
Ho开发者_如何学Gow do I write the constructor so that it sets the key 'name
' to 'james
'.
d = MyDict()
print d['name'] ....this should print out "james"
In (C)Python 2.5.2:
>>> class MyDict(dict):
... def __init__(self, *args, **kwargs):
... super(MyDict, self).__init__(*args, **kwargs)
... self['name'] = 'james'
...
>>> d = MyDict()
>>> print d['name']
james
A basic subclass of dict will allow basic storage:
class MyDict(dict):
def __init__(self, *args):
super(MyDict, self).__init__(*args, **kwargs)
self['name'] = 'james'
For more complicated storage, you may want to look into __setitem__ and __getitem__
精彩评论