A summary of __init__, __new__, __call__ in Python _python

Source: Internet
Author: User

1.__new__ (CLS, *args, **kwargs) is invoked when an object is created, returning an instance of the current object; Note: The first argument here is the CLS, the class itself.
2.__init__ (self, *args, **kwargs) is invoked after the object is created, with some initialization of the instance of the current object, no return value, that is, after the call to __new__, based on the returned instance; Note that the first argument here is self, the object itself. Notice the difference with new "
3.__call__ (self, *args, **kwargs) If the class implements this method, it is equivalent to using this type of object as a function, equivalent to overloading the bracket operator

See the specific example:

Copy Code code as follows:

Class O (object):

def __init__ (self, *args, **kwargs):
Print "Init"
Super (O, self). __init__ (*args, **kwargs)

Def __new__ (CLS, *args, **kwargs):
Print "New", CLS
Return Super (O, CLS). __new__ (CLS, *args, **kwargs)

def __call__ (self, *args, **kwargs):
Print "Call"

oo = O ()
Print "________"
OO ()


The print out is:
Copy Code code as follows:

New
Init
________
Call

For example: Python Singleton (single case mode) implementation, then we are not just overloading some __new__ methods on it
Copy Code code as follows:

Class Singleton1 (object):
"" "Overload New Method" ""
Def __new__ (CLS, *args, **kwargs):
If not ' _instance ' in VARs (CLS):
Cls._instance = Super (Singleton1, CLS). __new__ (CLS, *args, **kwargs)
Return cls._instance

Can you overload the __init__ method? Obviously not, because __init__ before the __new__ method, this time has generated an object, no way to implement a single case pattern

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.