我如何正确地子类化“dict”?

时间:2011-07-17 05:51:30

标签: python oop

class MyDict(dict):
    def __init__(self, *args):
        #fill in here

如何编写构造函数,以便将键“name”设置为“james”。

d = MyDict()
print d['name'] ....this should print out "james"

2 个答案:

答案 0 :(得分:2)

在(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

答案 1 :(得分:0)

dict的基本子类将允许基本存储:

class MyDict(dict):
    def __init__(self, *args):
        super(MyDict, self).__init__(*args, **kwargs)
        self['name'] = 'james'

对于更复杂的存储空间,您可能需要查看__setitem____getitem__