Python __missing__ 魔法方法

本文探讨了如何在Python字典中使用自定义的__missing__方法来处理键不存在的情况,与默认的KeyError异常进行对比,并通过实例展示了如何在继承dict并重写__getitem__方法时实现这一功能。
摘要由CSDN通过智能技术生成
  • 首先从使用一个字典开始, 当以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__, 并将返回值返回.


官方文档描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值