如何重新加载__getitem__,以便在键不存在时可以创建它 [英] How can reload __getitem__ so that, when key doesn't exist, can create it
问题描述
是否可以创建尚不存在的键值,重新加载方法__ getitem __?
Is it possible to create a key value that does not yet exist, reload the method __ getitem__?
我尝试:
class Dict_(dict):
def __getitem__(self, key):
if key in self:
self[key] = {}
return self[key]
else:
return self[key]
我了解为什么会有堆栈溢出,但我不明白为什么没有溢出
I understand why there is a stack overflow, but I do not understand why there is no overflow
class Dict_(dict):
def __getitem__(self, key):
if key not in self:
self[key] = {}
return self.get(key)
else:
return self.get(key)
请参见说明,并发现使用get时也使用__ getitem__-D [k]
See description and see that when using get also uses __ getitem__ - D[k]
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
请告诉我,如何通过 __ getitem __
做我想做的事情?
Please tell me, how to do what I want through __getitem__
?
推荐答案
需要调用原创 __getitem__
;使用 self [key]
调用顶级 __ getitem __
并创建无限递归.
You need to call the original __getitem__
; using self[key]
calls the top-level __getitem__
and creates an infinite recursion.
执行此操作:
class Dict_(dict):
def __getitem__(self, key):
if key not in self:
self[key] = {}
return super(Dict_, self).__getitem__(key)
请注意,内置的Python dict
类型已经支持您的用例.如果您定义 __ missing __()
方法,它将被称为自动:
Note that the built-in Python dict
type already has support for your use-case; if you define a __missing__()
method it'll be called automatically:
class Dict_(dict):
def __missing__(self, key):
self[key] = {}
return self[key]
这是 collections.defaultdict()
确实,提供了一个 __ missing __
方法,该方法调用了提供的工厂方法:
This is what collections.defaultdict()
does, provide a __missing__
method that calls a provided factory method:
somedict = collections.defaultdict(dict)
这篇关于如何重新加载__getitem__,以便在键不存在时可以创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!