我改变了 getitem 特殊方法,用python字典实现了perl的自动修复功能,如下所示:
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
这非常有用,但是现在我找不到返回创建对象的字典原始类的方法。首先,有可能吗?
答案 0 :(得分:1)
这是一种可以关闭该功能的方法:
class AutoVivification(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.vivify = True
self.root = self
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
if not self.root.vivify:
raise
value = self[item] = type(self)()
value.root = self.root
return value
def unvivify(self):
self.vivify = False
用法:
a = AutoVivification()
a['b']['c'] = 3
print(a)
a.unvivify()
print(a['b']['d'])
输出:
{'b': {'c': 3}}
Traceback (most recent call last):
File "/Users/alexhall/Dropbox/python/books/sandbox/sandbox.py", line 25, in <module>
print(a['b']['d'])
File "/Users/alexhall/Dropbox/python/books/sandbox/sandbox.py", line 9, in __getitem__
return dict.__getitem__(self, item)
KeyError: 'd'