我更改了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这是非常有用的,但是现在我没有找到返回创建对象的字典原始类的方法。第一,是否可能?
发布于 2016-12-12 18:32:21
下面是关闭该功能的一种方法:
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'https://stackoverflow.com/questions/41106022
复制相似问题