开发者

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__

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜