让你的字典读取不报错

谢乾坤|青南 at 
让你的字典读取不报错的配图
我们知道,读取 Python 字典时,如果某个 Key 不存在,Python 就会报错,如下图所示:为了防止它报错,我们可以使用.get()方法:但每次都要写.get()稍显麻烦。于是我们可以通过自己实现一个自定义的字典对象,来解决这个问题。我们自定义一个类,继承 dict,然后实现它的__missing__方法:123456class OurDict(dict): def __missing__(self, key): return Nonea = OurDict({'a': 1, 'b': 2})print(a['x'])运行效果如下图所示:只要这个 Key 不存在,就……