Python detailed class class constructor __new__ and initialization function __init__ (eight)

Source: Internet
Author: User
Tags in python

How to construct a class from the basic cognition class to the attribute, method, access control, inheritance and restriction of the deep cognition class.

1. Class construction and initialization

We define a class and generate an initialization _ _ init _ _ Object Function And _ _ _ New _ Object function:

Class A (object):
    def __init__ (Self,*args, **kwargs):
        print ("init%s"%self.__class__)
    def __new__ (cls,* args, **kwargs):
        print ("new%s"%cls) return
        object.__new__ (CLS, *args, **kwargs)

a = A ()
New <class ' __main__. A ' >
init <class ' __main__. A ' >


as can be seen from the results, when instantiating Class A, the "_ _new _ _" method is called first, followed by "_ _ Init _ _" method.

Generally speaking, the "_ _ init _ _" and "_ _ new_ _" Functions all have the following form:

def __init__ (self, *args, **kwargs):
    # func_suite

def __new__ (CLS, *args, **kwargs):
    # Func_suite
return obj

for "_ _new _ _" and "_ _ init _ _" can be summarized as: The "_ _new _ _" method is the real construction method in Python (creating and returning an instance), by which a "CLS" corresponding to an instance object can be generated, so the "_ _ _ New _" Method must have a return to In the "_ _ Init _ _" method, is an initialization method,"Self" represents the class generated by the instance object , "_ _ init _ _" will be the corresponding initialization of this object

The previous article has introduced the "_ _ init _ _" Some of the behavior, including inheritance in the "_ _ init _ _" performance. The following is the key to see "_ _ New _ _" method.

2, _ _ new_ _ Characteristics
"_ _ _ New_ _" is a new way to appear in the modern class, it has the following behavioral characteristics: The "_ _ _ New_ _" method is the first method invoked when the class instantiates the object , and returning the instance object "_ _ New_ _" method is always a class method (that is, the first parameter is the CLS The CLS is the class currently being instantiated , even if the first parameter is not added to the adorner. If you want to get an instance of the current class, you should call the "_ _ New_ _" Method for the parent class of the current class in the "_ _ New _" method statement in the current class for the 3rd above, If the current class is directly inherited from object, the "_new_" method of the current class should return an object that is:

Def __new__ (CLS, *args, **kwargs):
  # Func_suite return
  object.__new__ (CLS, *args, **kwargs)

2.1, Rewrite _ _ new_ _

If the (new) class does not rewrite the _ _ _ New _ method, Python defaults to the "_ _ _ New_ _" Method of calling the class's direct parent class to construct an instance of the class, and if the parent class of the class does not override "_ _ New _", the same rule is traced back to the object "_ _new_ _" method, because object is the base class for all new classes .

And if the "_ _new_ _ " method is overridden in a new class, you can choose any other new class ( must be a new class, only the new class has "_  _ new_ _  , because the "__ _ new _ _" method for all new classes is derived from Object creates an instance, including all the previous generations and descendant classes of this new class. As long as they do not cause recursive death loops.

Class Fun (object): Def __new__ (CLS, *args, **kwargs): obj = object.__new__ (CLS, *args, **kwargs) # The object.__new__ (CLS, *args, **kwargs) here is equivalent to Super (Fun, CLS). __new__ (CLS, *args, **kwargs) # object.__new__ (Fun, *args, **kwargs) # ny.__new__ (CLS, *args, **kwargs) # person.__new__ (CLS, *args, **kwargs), even though the person is not related to fun The system is also allowed because the person is a new class derived from object # in any new class, it cannot invoke its own ' __new__ ' to create an instance, because it causes a dead loop # so avoid return fun.__new__ (CLS, *a  RGS, **kwargs) or return cls.__new__ (CLS, *args, **kwargs) print (' Call __new__ for%s '%obj.__class__) return   
        Obj class Ny (Fun): Def __new__ (CLS, *args, **kwargs): obj = object.__new__ (CLS, *args, **kwargs) Print (' Call __new__ for%s '%obj.__class__) return to obj class Person (object): # The person has no "__new__" method, then
        Automatically calls the "__new__" method of its parent class to create an instance, which automatically invokes the object.__new__ (CLS) Pass class Girl (object): Def __new__ (CLS, *args, **kwargs):
 # You can choose to use bar to create an instance       obj = object.__new__ (Ny, *args, **kwargs) print ("Call __new__ to%s"%obj.__class__) return obj Fun = Fun () NY = NY () girl = Girl ()
Call __new__ for <class ' __main__. Fun ' > Call
__new__ for <class ' __main__. Ny ' > Call
__new__ for <class ' __main__. Ny ' >

2.2, _ _ _ init_ _ 's Call
"_ _ _ New _" Decides whether to use the "_ _ _ Init_ _" Method of the class, because "_ _ _ _ _" Can call other classes ' construction methods or directly return objects created by other classes as an instance of this class.

Typically, when a new class begins to instantiate, "The _ _ _ New _ method returns an instance of the CLS (CLS refers to the current class) and then calls the" _ _ Init_ _ "method of the class as an initialization method that receives the instance (that is, self) as its first argument, and then passes in" _ _n Position and named parameters received in the EW _ _ method.

However, if "_ _ _ New _" Does not return an instance of the CLS (that is, the current class), the "_ _ Init_ _" Method for the current class is not invoked. Look at the following example:

Class A (object):
    def __init__ (self, *args, **kwargs):
        print ("Call __init__ from%s"%self.__class__)

    def __ New__ (CLS, *args, **kwargs):
        obj = object.__new__ (CLS, *args, **kwargs)
        print ("Call __new__ for%s"%obj.__class (__) Return
        obj   

class B (object):
    def __init__ (self, *args, **kwargs):
        print (' Call __init__ from%s '% self.__class__

    def __new__ (CLS, *args, **kwargs):
        obj = object.__new__ (A, *args, **kwargs)
        print ("Call __new__ for%s '%obj.__class__ ' return
        obj      


b = b ()
print (type (b))
Call __new__ for <class ' __main__. A ' >
<class ' __main__. A ' >


2.3, derived immutable types about the "_ _ New_ _" method also has an important use is to derive immutable types.

For example, float in Python is an immutable type, and if you want to derive a subclass from float, you implement the _ _ _ New _ Method:

Class Roundtfloat (float):
    def __new__ (CLS, num):
        num = round (num, 4) return
        super (Roundtfloat, CLS). __new_ _ (CLS, num)
# return         float.__new__ (CLS, num)

num = roundtfloat (3.141592654)
print (num)   #3.1416
Print (num.__class__)
3.1416
<class ' __main__. Roundtfloat ' >


3. Customize a class in Python, we can use the "magic method" to make our custom class powerful and easy

This paper introduces the construction and initialization of class: "_ _ _ New _" and "_ _ init _ _". The "_ _ _ New _" Method is a new class-specific method, in which case the _ _ New _ method creates an instance of the CLS (CLS refers to the current class) and calls the "_ _ Init _ _" method of the class as the initialization method, which The method receives this instance (that is, self) as its first argument, then pass in the "_ _ _ _" method to receive the position and named parameters, but if "_ _ _ _" does not return an instance of the CLS (that is, the current class), then the current class "_ The _ init _ _ method is not invoked.



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.