Learn more about _ new _ and _ call __, and know _ new ___ call _
1. About _ init __
Class F00 (object ):
Def _ init _ (self, name ):
Self. name = name
Print ("Foo -- init --")
Def _ new _ (cls, * args, ** kwargs ):
Print ("Foo -- new --")
Return object. _ new _ (cls) # cls indicates passing the Foo class into the _ new _ method, which indicates the _ new _ method of the stepfather class.
F = F00 ("name ")
# If return object exists. when _ new _ (cls), Foo -- new -- And Foo -- init -- are output successively, indicating that _ new _ is executed before _ init _.
# When return object. _ new _ (cls) is removed, only Foo -- new -- is output, indicating that the _ init _ instance is not attached to the instance.
# Conclusion: The __new _ method is built-in in the class. The new method is used to create instances. It is not written by default and can be rewritten.
# Function: it is executed before _ init _ during instantiation. We want
2. About _ call __
Class MyType (type ):
Def _ init _ (self, what, bases = None, dict = None ):
Super (MyType, self). _ init _ (what, bases, dict)
Def _ call _ (self, * args, ** kwargs ):
Obj = self. _ new _ (self, * args, ** kwargs)
Self. _ init _ (obj)
Class Foo (object): # The underlying layer is implemented through the _ init _ method of the MyType class.
_ Metaclass _ = MyType
Def _ init _ (self, name): # The underlying layer is implemented through self. _ init _ (obj) of the _ call _ method of the MyType class.
Self. name = name
Def _ new _ (cls, * args, ** kwargs ):
Return object. _ new _ (cls) # The underlying layer is obj = self through the _ call _ method of the MyType class. _ new _ (self, * args, ** kwargs) implemented
Obj = Foo ("name") # The _ call _ method of the MyType class is used to execute the instance for creating Foo.
#__ Call _ used to create _ new _