Python in __init__ (), __new__ (), __call__ (), __del__ () usage

Source: Internet
Author: User

Http://www.myhack58.com/Article/68/2014/48183.htm

Body:

The usage of __new__ ():

__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.
# Encoding:utf-8class A (object):    def __new__ (CLS, x):        print ' This was in a.__new__, and X is ', X        return Super ( A, CLS). __new__ (CLS)    def __init__ (self, y):        print ' This is in a.__init__, and Y is ', Yclass C (object):    def __  new__ (CLS, n):        print ' This was in c.__new__, and N is ', N        return Super (C, CLS). __new__ (CLS)    def __init__ (self, A):        print ' This was in c.__init__, and A are ', AClass B (a):    def __new__ (CLS, z):        print ' This was in b.__new__ , and Z is ', z        return a.__new__ (CLS, z)    def-__init__ (self, m):        print ' This is in b.__init__, and M-is ', M # class B (A): #     def __new__ (CLS, z): #         print ' This was in b.__new__, and Z is ', z#         return object.__new__ (CLS) #     def __init__ (self, M): #         print ' This is Ni-b.__init__, and M is ', mif __name__ = = ' __main__ ':    a = a (100) C21/>print ' = ' *    B = b (+)    print type (b)

The result of the execution is:

This are in a.__new__, and X are  100this is in a.__init__, and Y are  100====================this are in b.__new__, and Z is  200this are in a.__new__, and X is  200this are in b.__init__, and M is  200<class ' __main__. B ' >

Description

1. Define Class A as the parent class of the following class, Class A inherits the object class, because it is necessary to rewrite the __new__ () function of Class A, so we need to inherit the object base class, become the new class, the classic class does not have __new__ () function;

2. When overriding the __new__ () function, the subclass must return the __new__ () function Call of the class with the inheritance relationship, that is, Class B in the above code inherits from Class A, then overrides the Class B __new__ () function, and when writing return, it can only return a.__new__ ( CLS) or object.__new__ (CLS), cannot return class C;

3. The result of the commented code execution shows that although Class B inherits from Class A, if the __new__ () function of Class B is not overridden, the default inheritance is still the __new__ () of the object base class, not A;

The __new__ () function of the 4.B class is called when the Class B is instantiated, and the code statements in it are executed automatically, but overriding the __new__ () function does not affect the instantiation of the class, meaning that the instantiation object of Class B is the Class B, regardless of whether a or object is returned when the return is written. , but does not become an instantiated object of Class A, but when instantiated, the __new__ () function defined in Class A is executed if a.__new__ (CLS) is returned;

The 5.__new__ () function determines the number of arguments to the class, the parameter of the __new__ () function defined by the object class is (CLS, *more), but if __new__ (CLS, x) is overridden in a subclass, it is necessary to pass in an x parameter when instantiating the class, and __ The init__ () function accepts two arguments, one that instantiates the generated instance object, and one that is the value of the passed argument x;

attribute of the __new__ () method: The __new__ () method is called when the class prepares itself for instantiation. The __new__ () method is always a static method of the class, even if the static method adorner is not added. Because no matter how the __new__ () function of the class is overridden, the trace to the source is the __new__ () function that inherits from object, and the __new__ () function defined in the object class is defined as a static function, which is @stacitmethod decorated

The instantiation of     class and how it is constructed are usually the same: Class MyClass (object):   def __init__ (self, *args, **kwargs):       ...# Instantiation MyClass = MyClass (*args, **kwargs) as shown above, a class can have multiple positional parameters and multiple named parameters, and after the instantiation begins, before the __init__ () method is called , Python first calls the __new__ () 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 current class's __new__ () method should be: Def __new__ (CLS, *args, **kwargs):   ...   return OBJECT.__NEW__ (CLS) Note: In fact, if the __new__ () method is not overridden in the (modern) class, that is, when the new class is defined without redefining __new__ (), Python defaults to the __new__ () of the immediate parent class that called the class. method to construct an instance of the class, and if the parent class of the class does not override __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. specifically see the following code explanation: Class Foo (object):    def __init__ (self, *args, **kwargs):        ...  &nbsp ; Def __new__ (CLS, *args,**kwargs):        return object.__new__ (CLS, *args, **kwargs)        # above ret Urn equivalent to  # return object.__new__ (foo, *args, **kwargs)     class child (foo):    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 manufacture the instance, 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 important to avoid the following notation: # in Foo avoid: 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):    ... # When a stranger instance is manufactured, object.__new__ (CLS) is called automatically when the new class begins to instantiate, the __new__ () The __init__ method returns an instance of the CLS (CLS refers to the current class), and then the class's () method as a constructor receives the instance (that is, self) as its first argument, and then in turn passes in the position parameter and named parameter received in the __new__ () 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 result of nbsp;# 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, give the Class A shell to create the instance framework, 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;  two, __init__ () usage __init__ () is a construction method of Python, when defining a class, some of the operations used to initialize it, the functions and principles it can implement are relatively simple, that is, when instantiating the class, automatically executes the contents of the __init__ () method definition; but note __init__ () Generally no user returns return;
>>> >>> class A (object):    def __init__ (self, x):        self.x = x        print ' __init__ called. '    def foo (self):        print self.x        

When a class is instantiated in a (' 123 '), the self.x = x and print ' __init__ called defined by the __init__ () method are called automatically. ' We can see ' __init__ called. ' is printed, not seen self.x = x executed, However, when calling A.foo (), the ability to execute succeeds is given by the function of self.x = x, because if there is no self.x = x in the __init__ () method, the instance object will not be traced back to where the self.x in the Foo () function came from, thus giving an error; The init__ () function assigns an externally passed parameter x to self.x, which is self.x in Class A;

Three. Use of __call__ ()

The __call__ () method enables an instance object of a class to be called like a function;

>>> >>> class A (object):    def __call__ (self, x):        print ' __call__ called, print x: ', x        >& gt;> >>> a = A () >>> a (' 123 ') __call__ called, print x:  

Look at a (' 123 ') This is the function of the call method, where a is actually a class object A instance object, the instance object can be like the function of the same argument and be called, is the function of the __call__ () method;

Iv. usage of __del__ ()

If the __new__ () and __init__ () functions are constructors of the class (that is, the content defined in the function is automatically executed when the class is instantiated), then __del__ () is the destructor of the class and is the actual application of the Python garbage collection mechanism, when all references to the class are deleted. The class is removed from memory by the system, and note that all references are deleted, not every deletion;

>>> class D (object):    def __init__ (self):        print ' This is d.__init__ () '    def __del__ (self):        print ' This is d.__del__ () '        

The D () instantiation object is assigned to D, and after D2,d3 is the instantiation object that points to D (), the deletion of references to D and D2 does not trigger the __del__ () function, and the last D3 reference is deleted, triggering __del__ (), at which point the instantiated object of D () is cleared;

At last:

Use a simple code to get a general feel for the usage and differences of the three methods:

>>> >>> class A (object):    def __init__ (self, x):        print ' x in __init__ ', x    def __new__ (CLS, y ):        print ' Y in __new__ ', Y        return super (A, CLS). __new__ (CLS)    def __call__ (self, z):        print ' Z in __call__ ' , Z    def __del__ (self): "print ' This was in        a.__del__ () '        

As can be seen from the execution results, although the __init__ () method is defined before the __new__ () method, the results of the __new__ () method are shown first.

Python in __init__ (), __new__ (), __call__ (), __del__ () usage

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.