Python's __init__, __new__ magic Method, and its use in the __metaclass__ meta class

Source: Internet
Author: User

The instantiation of a class in Python is done by the Python interpreter calling __new__,__init__, which is used to complete the "skeleton" of the instantiated object (for example, the interpreter assigns an address to the object and returns a reference value that points to the object. The reference value is then passed to the __INIT__ function, which "fills" the instantiated object in such a way as "self. Property Name = property value".

1.__new__

In the process of instantiating an object in a class (assuming Class A), the __new__ () method is preceded by the __init__ () method call, which returns a reference to an instance of a, which is passed to the next executing method, and if __new__ () does not return a reference to an instance, then _ _INIT__ () will not be executed if it returns an instance of non-a (syntactically, but meaningless) B (assumed to be an instance of B), it continues to execute the __init__ () method of B.

__new__ (cls[, ...] ), thefunction form of the __new__ () method is shown on the left. It is a static method (although there is no modifier to use static methods), the value of the CLS is a class, and the other parameters are the arguments passed to the constructor when it is initialized (that is, the arguments passed to __init__ (), for example, a = A ("Jonhn", 20) such a statement, The interpreter automatically invokes __new__ (A, "JONHN", 20) when instantiating a, and the interpreter passes a and the collected parameters to __new__ (), giving it the ability to manipulate the data. Therefore , when defining __new__ (), the parameters are best set to coincide with __init__ (), especially if the *args,**kwargs is used, after the default value, to ensure that the defined formal parameters are properly accepted by the arguments.

classPerson ():def __init__(self, Name, age): Self.name=name Self.age= Agedef __new__(CLS, *args, * *Kwargs):Print("__new__ Method is invoking")        returnSuper (person, CLS).__new__(CLS) p= Person ("John", 30)Print(p.name)Print(P.age)

Operation Result:

__new__  is Invokingjohn30

When it comes to inheritance, the general form of the __new__ () method that invokes the ancestor class is "

Typical implementations create a new instance of the class by invoking the superclass ' s __new__ () method using super (Currentclass, CLS). __new__ (cls[, ...]) With appropriate arguments and then modifying the newly-created instance as necessary before returning it.

When it comes to inheritance, derived classes are instantiated in terms of the MRO search __new__ (__init__ is the same) and called, which should also be noted when designing a class system.

Use cases for 2.__new__

"__new__ () is intended mainly to allow subclasses of immutable types (like Int., STR, or tuple) to customize Insta NCE creation. It is also commonly overridden in the custom metaclasses in order to customize class creation. "

A generic custom class is an abstraction of the same kind of thing, and all of these custom classes are abstracted, and their common feature is that they can be instantiated, and the custom class can be abstracted into an instance of type (a good dialectical idea, a class, a moment, and then an instance). After the type is instantiated, a class is given, and type is called a meta-class, and we can create our own meta-classes based on the requirements, using the modules in the project so that these classes have some common features that we want to implement.

This article gives a number of use cases:

A brief analysis of Python's metaclass

Python's __init__, __new__ magic Method, and use in the __metaclass__ meta-class

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.