- 首先从使用一个字典开始, 当以d[key] 方式取出一个不存在的值的时候, 会抛出
KeyError
的异常
d = {'a': 1, 'b': 2, 'c': 3}
print(d['a'])
print(d['f'])
# >>>>>>>>>>
1
Traceback (most recent call last):
File "D:/workspace/example-code/03-dict-set/test.py", line 17, in <module>
print(d['f'])
KeyError: 'f'
- 继承
dict
类
class NewDict(dict):
def __getitem__(self, item):
print(f'__getitem__被调用')
try:
ret = super(NewDict, self).__getitem__(item)
print(f'结果为: {ret}')
except Exception as e:
print(e)
raise e
return ret
nd = NewDict(a=1, b=2)
print(nd['a'])
# >>>>
__getitem__被调用
结果为: 1
1
# >>>>>
print(nd['c'])
__getitem__被调用
Traceback (most recent call last):
File "D:/workspace/example-code/03-dict-set/test.py", line 18, in <module>
print(nd['c'])
File "D:/workspace/example-code/03-dict-set/test.py", line 13, in __getitem__
ret = super(NewDict, self).__getitem__(item)
KeyError: 'c'
可以看出在我们使用d[key]方式取值的时候调用的是 getitem 方法,找到不到 key, 抛出 KeyError 异常
- 实现
__missing__
方法
class NewDict(dict):
def __missing__(self, key):
print(f'__missing__被调用')
return 1000
def __getitem__(self, item):
print(f'__getitem__被调用')
ret = super(NewDict, self).__getitem__(item)
return ret
nd = NewDict(a=1, b=2)
print(nd['a'])
# >>>>>>>>
__getitem__被调用
1
# >>>>>>
print(nd['c'])
__getitem__被调用
__missing__被调用
1000
可以看出当我们实现了 __missing__
方法, 以d[key] 方式取值. 当有此key的时候,是不会调用 __missing__
方法, 当 key 不存在的时候, 会调用 __missing__
, 并将返回值返回.