__new__ and __init__ in Python

Source: Internet
Author: User

Characteristics of the __new__ () method:

    • The __new__ () method is called when the class prepares to instantiate itself.

    • The __new__ () method is always a static method of the class, even if the static method adorner is not added.

Class A (object): Def __init__ (self): print "Init" def __new__ (Cls,*args, **kwargs): print "new%s"% CLS return object.__new__ (CLS, *args, **kwargs) A ()

Output:

New <class ' __main__. A ' >
Init

Knowledge Points:

New classes that inherit from Object have __new__.

__new__ must have at least one parameter CLS, which represents the class to instantiate, which is automatically provided by the Python interpreter when instantiated.

__new__ must have a return value to return the instantiated instance, which should pay special attention when implementing __new__, can return the instance that the parent class __new__ out, or the __new__ of object directly.

__INIT__ has a parameter, self, which is the instance returned by this __new__, __init__ can perform some other initialization actions based on __new__, __init__ does not need a return value.

If __new__ does not correctly return an instance of the current class CLS , the __init__ will not be called, even if it is an instance of the parent class.

Class A (object): Pass class B (A): def __init__ (self): print "Init" def __new__ (Cls,*args, **kwargs): Print "New%s"%cls return object.__new__ (A, *args, **kwargs) b=b () print type (b)

Output:

New <class ' __main__. B ' >
<class ' __main__. A ' >


Resources:

Http://www.cnblogs.com/ifantastic/p/3175735.html

Http://www.cnblogs.com/tuzkee/p/3540293.html

__new__ and __init__ in Python

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.