Learn more about _ new _ and _ call __, and know _ new ___ call _

Source: Internet
Author: User

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 _

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.