[英]How do I properly subclass a “dict”?
class MyDict(dict):
def __init__(self, *args):
#fill in here
How do I write the constructor so that it sets the key ' name
' to ' james
'.如何编写构造函数,以便将键“
name
”设置为“ james
”。
d = MyDict()
print d['name'] ....this should print out "james"
In (C)Python 2.5.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
A basic subclass of dict will allow basic storage: dict 的基本子类将允许基本存储:
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__对于更复杂的存储,您可能需要查看__setitem__和__getitem__
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.