正如其他人所解释的那样,
super()
在这里不工作是因为它返回一个
超级对象
,它是一个代理对象,处理按方法解析顺序将点式属性访问分派给下一个类。
尽管如此,你不应该凌驾于
__getitem__
在这里,python数据模型提供了一些
就为了这个案子
,它是
__missing__
method
:
object.__missing__(self, key)
实施
self[key]
当键不在
字典。由调用
dict.__getitem__()
所以,这样做:
class ZeroDict(dict):
def __missing__(self, key):
if 0 in key:
return 0
else:
raise KeyError(key)
还有一个演示:
>>> class ZeroDict(dict):
... def __missing__(self, key):
... if 0 in key:
... return 0
... else:
... raise KeyError(key)
...
>>> d = ZeroDict()
>>> d[(1, 0)] = 'foo'
>>> d
{(1, 0): 'foo'}
>>> d[1, 0]
'foo'
>>> d[1, 1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __missing__
KeyError: (1, 1)
>>> d[0, 1]
0
>>>