In addition, there is another implementation method of AutoVivification, which is to directly overload dict's __missing__magic method. Think of it as an extension.
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __missing__(self, key):
value = self[key] = type(self)()
return value
One more thing, Python 2.5 and later versions added the collections.defaultdict type, which can customize a more scalable dict type. collections.defaultdict 类型,该类型可以自定义扩展性更强大的dict类型。 文档中指出,其实现原理就是重载了 __missing__The documentation points out that the implementation principle is to overload the
method. AutoVivification can also be expressed like this:
__missing__defaultdict constructs a dict type whose first parameter is its default_factory. When is called, the return value is constructed using default_factory. More examples of defaultdict🎜
You can implement this structure yourself.
In the example below, AutoVivification inherits from dict
We can use AutoVivification like this:
Output:
In addition, there is another implementation method of AutoVivification, which is to directly overload dict's
__missing__
magic method. Think of it as an extension.One more thing, Python 2.5 and later versions added the
method. AutoVivification can also be expressed like this:collections.defaultdict
type, which can customize a more scalable dict type.collections.defaultdict
类型,该类型可以自定义扩展性更强大的dict类型。文档中指出,其实现原理就是重载了
__missing__
The documentation points out that the implementation principle is to overload the__missing__
defaultdict constructs a dict type whose first parameter is its default_factory. Whenis called, the return value is constructed using default_factory. More examples of defaultdict🎜
I will attach the usage of defaultdict package:
Output:
This way you can achieve the desired effect,
Added:
defaultdict() receives a default parameter, which can be a type name or any callable function without parameters
This is very easy to use
Output: