我想创建SafeDict
,一个dict
的子类
当要求检索不存在的键的值时,SafeDict
应返回回退值。
(我知道还有其他方法可以做到这一点,但我正在练习我的OOP技巧。)
现在我有:
class SafeDict(dict):
def __getitem__(self, key):
try:
super().__getitem__(key)
except KeyError:
return "Beetle"
a = {"Ford": "Mustang"}
b = SafeDict({"Ferrari": "Enzo"})
print(a["Ford"]) # This prints "Mustang" (good)
#print(a["Aston"]) # This raises KeyError (good)
print(b["Ferrari"]) # This should print "Enzo", but it prints "None" (bad)
print(b["Aston"]) # This prints "Beetle" (good)
可能print(b["Ferrari"])
打印None
,因为super()
在list
超类上运行__getitem__
方法,而该类中没有包含"Ferrari": "Enzo"
的字典
我试图删除super()
,并使用self
,但遇到了递归问题
救命啊
您忘记返回super()值:
当方法没有显式的
return
语句时,函数将隐式返回None
相关问题 更多 >
编程相关推荐