Python __new__ and __init__

Source: Internet
Author: User

@[Deep python]__new__ and __init__
12345678 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:

A new class that inherits from Object has __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 be paid special attention when implementing __new__, you can return an instance of the parent class __new__, or an instance that is directly an object __new__.

__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

123456789101112 class A(object):    passclass 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 ' >

[Python] __new__ () method and instantiation of Python

__new__ () is a newly emerging method in a new class that, before the construction method constructs an instance, can understand that the construction method that exists in the class in Python __init__ () is responsible for instantiating the class, and before __init__ () starts, __new__ () Decide whether you want to use the __init__ () method, because __new__ () can call the constructor of another class or return directly to another object as an instance of this class.

If the class is likened to a factory, then the __init__ () method is the production worker of the factory, and the __init__ () method accepts the initialization parameters that are required to produce the raw material, and the __init__ () method is responsible for processing the raw material into an instance for the factory to ship according to the statement in the method. While __new__ () is the production manager, the __new__ () method can decide whether to supply the raw material to the production worker, and it also determines whether the shipment is the product of the production department, since the manager can sell the product to the customer in the name of the plant, which is not the factory at all.

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.
    • The instantiation of a class and how it is constructed are usually the same way:
Class MyClass (object):    __init__ (self, *args, * *Kwargs):        ... # instantiation of MyClass = MyClass (*args, **kwargs)    

  

As shown above, a class can have multiple positional parameters and multiple named parameters, and after instantiation begins, Python calls the __new__ () method first before calling the __init__ () method:

__new__ (CLS, *args, * *Kwargs):    ...

  

The first parameter, the CLS, is the class that is currently being instantiated.

    • If you want to get an instance of the current class, you should call the __new__ () method of the parent class of the current class in the __new__ () method statement in the current class.

For example, if the current class is directly inherited from object, the object returned by the __new__ () method of the current class should be:

__new__ (CLS, *args, * *Kwargs):    ...    return object. __new__ (CLS)  

  

Attention:

  In fact, if the (new) class does not override the __new__ () method, that is, when the new class is defined without redefining __new__ (), Python defaults to calling the __new__ () method of the immediate parent class of the class to construct an instance of the class, if the parent class of the class is not overridden __new__ (), then the __new__ () method of the object is traced back to this rule because object is the base class for all modern classes.

And if the __new__ () method is overridden in the new class, then you are free to choose any of the other new classes (it must be the new class, only the new class must have __new__ (), because all the new classes are descendants of object, and the classic class does not have the __new__ () method) _ The _new__ () method is used to make an instance, including all the preceding and descendant classes of this new class, as long as they do not cause a recursive loop. See the following code to explain the details:

ClassFoo (object):Def__init__ (self, *args, * *kwargs): ... def __new__ (CLS, *args, * * kwargs): return object. 
# above return equals
# return object.__new__ (Foo, *args, **kwargs)
# return stranger.__new__ (CLS, *args, **kwargs)
# return Child._ _new__ (CLS, *args, **kwargs)
class Child (Foo): Span style= "color: #0000ff;" >def __new__ (CLS, *args, **kwargs): return object. __new__ (CLS, *args, **kwargs)
# if the __new__ () method is not defined in child, the __new__ () method of its parent class is automatically called to make the instance, namely foo.__new__ (CLS, *args, **kwargs).
# in any new class, the __new__ () method cannot call its own __new__ () to make an instance, because this causes a dead loop. It is therefore necessary to avoid writing similar to the following:
# Avoid in Foo: Return foo.__new__ (CLS, *args, **kwargs) or return cls.__new__ (CLS, *args, **kwargs). Child in the same vein.
# the __new__ () of a new class with object or no blood relationship is safe, but if it is between two classes that have an inheritance relationship, you should avoid cross-tuning causing a dead loop, such as: (Foo) return child.__new__ (CLS), (child) Return foo.__new__ (CLS).
Class Stranger (Object):    ...
# object.__new__ (CLS) is called automatically when a stranger instance is manufactured

    • In general, when a new class begins to instantiate, the __new__ () method returns an instance of the CLS (the CLS refers to the current class), and then the __init__ () method of that class takes the instance (that is, self) as its first argument, and then sequentially passes in to the __new__ () The location parameters and named parameters that are received in the method.

Note: if __new__ () does not return an instance of the CLS (that is, the current class), then the __init__ () method of the current class is not called. If __new__ () returns an instance of another class (either a modern class or a classic Class), then only the constructor of the returned class is called.

ClassFoo (object):def __init__ (Self, *args, * *    kwargs): ... def __new__ (CLS, *args, * * kwargs): return object.class Stranger (object): ... foo = Foo () print type (foo)  

# The result of printing shows that Foo is actually an instance of the Stranger class.

# So you can describe the difference between __new__ () and __ini__ (), in the new Class __new__ () is the real instantiation method, create an instance framework for the class to provide the shell, and then call the construction method within the framework __init__ () to make it plump.
# If building a house metaphor, the __new__ () method is responsible for developing the land, laying the foundation, and storing the material at the site. and the __init__ () method is responsible for the construction of the building from the site to build the Land development bid, __INIT__ () responsible for the details of the building design, construction, decoration so that it can be delivered to the customer.

Python __new__ and __init__

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.