Use and instantiation of the __new__ () method in Python

Source: Internet
Author: User

New () is a newly emerging method in the modern class that, before the constructor init () constructs an instance, it is understood that the constructor init () that exists in the class in Python is responsible for instantiating the class, and before the Init () call, new () determines whether 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 in accordance with the statements in the method. and new () is the production manager, the new () method can decide whether to supply the raw material to the production workers, and it also determines whether the shipment is the product of the production department, because the manager can use the name of the factory to sell to the customer is not exactly the plant's products.
Features 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):   def __init__(self, *args, **kwargs): ...# 实例化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:

def __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, then the object returned by the new () method of the current class should be:

def __new__(cls, *args, **kwargs):   ...   return object.__new__(cls)

In fact, if the new () method is not rewritten in the (new) class, that is, when new () is not redefined when the new class is defined, Python defaults to invoking the new () method of the immediate parent class of the class to construct an instance of the class, and if the parent class of the class does not override new (), The new () method of the object is then 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) to make the instance, Includes all of the preceding and descendant classes of this new class, as long as they do not cause recursive loops of death. See the following code to explain the details:

ClassFoo(object):Def__init__def __new__ return object.__new__ (CLS, *args, * * Kwargs) # above return equals # return object.__new__ (Foo, *args, * * Kwargs) # return stranger.__new__ (CLS, *args, **kwargs) # Return child.__new__ (CLS, *args, **kwargs) class child (Foo): def Span class= "Hljs-title" >__new__ (CLS, *args, **kwargs): return Object.__new__ (CLS, *args, **kwargs)           

#如果Child中没有定义new () method, the new () method of its parent class is automatically called to manufacture the instance,

Foo.__new__(cls, *args, **kwargs)

In any new class, the new () method cannot invoke its own new () to make an instance, because it 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).

New () is safe to use object or unrelated new classes, 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
Typically, 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 passes in 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.

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

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

So the difference between new () and INI () can be described so that new () is the real instantiation method in the new class, the instance framework is created for the class to provide the shell, and then the constructor method within the framework is called 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. The init () method is responsible for building the buildings specified in the land development tenders from the construction site, and Init () is responsible for the details of the building, construction, and decoration so that it can be delivered to the customer.

Use and instantiation of the __new__ () method 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.