__init__ function
When a class instance is created, the __init__ () method executes automatically after the class instance is created, similar to the build function. __INIT__ () can be used as a build function, but unlike a build function in other languages, it does not create an instance-it is just the first method that executes after your object is created. Its purpose is to perform some of the necessary initialization work for that object. By creating your own __init__ () method, you can override the default __init__ () method (the default method does nothing), and thus be able to decorate the object that you just created __init__ () requires a default parameter of self, which is equivalent to this.
__call function
There is an interesting syntax in Python, as long as the __CALL__ function is implemented when the type is defined, this type becomes callable.
In other words, we can use the object of this class as a function, which is equivalent to overloading the parentheses operator. In order to understand the role of Python in __setattr__, __getattr__, __delattr__, __call__, rewrite dict, extend its functionality.
1 classStorage (dict):2 #by using __setattr__, __getattr__, __delattr__3 #you can rewrite the dict to make it pass "." Called4 def __setattr__(self, Key, value):5Self[key] =value6 def __getattr__(self, key):7 Try:8 returnSelf[key]9 exceptKeyerror, K:Ten returnNone One def __delattr__(self, key): A Try: - delSelf[key] - exceptKeyerror, K: the returnNone - - #The __call__ method is used for the invocation of the instance itself - #Reach () the effect of the call + def __call__(self, key): - Try: + returnSelf[key] A exceptKeyerror, K: at returnNone - -s =Storage () -S.name ="Hello"#It's a __setattr__ role. - PrintS"name")#It's a __call__ role. - Prints["name"]#dict default Behavior in PrintS.name#It's a __getattr__ role. - delS.name#It's a __delattr__ role. to PrintS"name") + Prints["name"] - PrintS.name
The __init__,__call__ in Python