[英]Using super with __getitem__ versus subscript
我正在寫一個只有正整數元組作為鍵的dict
。 如果密鑰未知且元組的其中一個元素為1
,則查找應返回默認值0
。 任何其他未知密鑰都應該引發KeyError
。
這很好用:
class zeroDict(dict):
'''
If key not in dict and an element of the tuple is
a 1, impute the value 0.
'''
def __init__self():
super().__init__()
def __getitem__(self, key):
try:
return super().__getitem__(key)
except KeyError:
if 1 in key:
return 0
else:
raise
這不是:
class zDict(dict):
'''
If key not in dict and an element of the tuple is
a 1, impute the value 0.
'''
def __init__self():
super().__init__()
def __getitem__(self, key):
try:
return super()[key]
except KeyError:
if 1 in key:
return 0
else:
raise
當我嘗試從zDict
讀取值時,我得到TypeError: 'super' object is not subscriptable
。
實現之間的唯一區別是zeroDict
說
return super().__getitem__(key)
和zDict
說
return super()[key]
但是, help(dict.__getitem__)
打印
__getitem__(...)
x.__getitem__(y) <==> x[y]
這似乎說這兩個陳述是等價的。 這里發生了什么?
正如其他人所解釋的那樣, super()
在這里不起作用的原因是因為它返回一個超級對象 ,它是一個代理對象,它處理調度方法解析順序中下一個類的點屬性訪問。
話雖如此,你不應該在這里重寫__getitem__
,python數據模型只為這種情況提供了一些東西,它是__missing__
方法 :
object.__missing__(self, key)
當key不在字典中時,為dict子類實現
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
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.