【发布时间】:2014-05-30 04:47:49
【问题描述】:
使用此代码:
class MyDict(dict):
def __setitem__(self, k, v):
print 'assignment', k, v
self.__dict__[k] = v
nsg = MyDict()
nsg["b"] = 123
print "G is: ", nsg
打印出来
assignment b 123
G is: {}
如果我添加
def __str__(self):
return self.__dict__.__str__()
有效:
assignment b 123
G is: {'b': 123}
同样,如果我打印 G["b"],我会得到一个 KeyError,除非 __getitem__(self) 返回 self.__dict__[k]。
为什么没有自动找到父类dict,如__str__ 和__getitem__?
【问题讨论】:
标签: python dictionary derived-class