python - How do I make a subclass of "dict" that returns a fallback value when it can't find a value for a key?
问题描述
I want to create SafeDict
, a subclass of dict
.
When asked to retrieve a value for a non existing key, SafeDict
should return a fallback value.
(I know there are other ways to do this, but I'm practicing my OOP skills.)
Right now I have:
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)
Maybe print(b["Ferrari"])
prints None
beacuse super()
runs the __getitem__
method on the list
superclass, and that class has no dictionary with "Ferrari": "Enzo"
in it?
I tried to remove the super()
, and use self
, but I ran into recursion problems.
Help?
解决方案
You forgot to return the super() value:
class SafeDict(dict):
def __getitem__(self, key):
try:
return super().__getitem__(key)
except KeyError:
return "Beetle"
When a method has no explicit return
statement, the function implicitly returns None
推荐阅读
- java - Spring Boot:如何为删除其余模板编写单元测试用例
- html - 无法使用 flexbox 将项目对齐到中心
- html - 'mailto' 从静态站点提交表单数据的任何替代方法?
- java - swing中custome jcombobox的标题背景发生意外变化
- php - Google 日历中的空白白屏
- c# - Unity中的移动真的很慢
- configure - config.status:错误:找不到输入文件:`po/Makefile.in.in'
- python-3.x - 另一个单元格中等于零值的空白单元格应在 python、pandas 中返回 True
- r - 从 FedData 包中使用 R 中的 get_ssurgo 下载失败
- python - 我的自定义方言输出在处理 csv 文件时未使用双引号