This is the 20th day of my participation in the August Text Challenge.More challenges in August

preface


Sanmao once sighed:

“What is the mind like? There is a labyrinth that stretches thousands of miles across. There is no boat that can ferry people. Throughout life, we are learning how to be our own ferrymen.

You can watch this blogger’s article about installation and LocalizationVsCode download, Installation and LocalizationAs well asPython series: windows10 configuration Python3.0 development environment!After installation, restart VsCode!

This time introduce the magic method of classThe __new__ () method.Python3In aboutObject base class __new__()Methods:

@staticmethod # known case of __new__
    def __new__(cls, *more) : # known special case of object.__new__
        """ Create and return a new object. See help(type) for accurate signature. """
        pass
Copy the code

__new__ ()Create and return a new object. Colloquially: this magic property is used to create instance objects. Let’s take a look at how it creates objects.


On! understand

  1. __new__()Is a new method in a new class that acts before the constructor builds an instance.
  • It can be interpreted as follows:PythonA constructor that exists in a class__init__ ()Is responsible for instantiating the class while in__init__ ()And before I do that,__new__ ()Responsible for making such an instance object so that__init__ ()To enrich the instance object (add attributes, etc.).
  • At the same time:__new__()The method also determines whether it should be used__init__()Method, because__new__()You can call the constructor of another class or simply return another object as an instance of this class.
  1. __new__() Methods are always static methods of a class, even without a static method decorator.

In the analogy of a factory, the __init__() method is the factory’s production workers, the __init__() method takes the initialization parameters as the raw materials needed for production, and the __init__() method takes care of processing the raw materials into instances for the factory to ship according to the statements in the method. __new__() is the manager of the production department. The __new__() method determines whether to supply the raw material to the workers in the production department. It also determines whether the shipped product is the product of the production department, because the manager can use the name of the factory to sell products to customers that are not the factory at all.


structure

inPython, if you do not override the class__new__()The default structure of the method looks like this:

class Foo(object) :
    def __new__(cls,*args,**kwagrs) :
        return super().__new__(cls,*args,**kwagrs)
Copy the code

1. Its first parameterclsIs the class currently being instantiated.

If you want to get an instance of the current class, it should be in the current class__new__()Method statement that calls the parent of the current class__new__()Methods. For example, if the current class inherits directly from Object, then the current class__new__()The object returned by the method should be:

class Foo(object) :
    def __new__(cls,*args,**kwagrs) :
        return object.__new__(cls,*args,**kwagrs)
Copy the code

Note: ① if (new) class is not overwritten__new__()Method that is not redefined when a new class is defined__new__()Python defaults to calling the class’s immediate parent__new__()Method to construct an instance of the class if the class’s parent has not been overridden either__new__(), will always follow this rule back toThe object of __new__ ()Method, becauseobjectIs the base class for all new classes.

② if the new class is overwritten__new__()Method, then you are free to choose any of the other new classes (must be new classes, only new classes must have both__new__()Because all the new classes are descendants of Object and the classical classes are not__new__() Methods)__new__()Method to create instances of this new class, including all its predecessors and descendants, as long as they do not create recursive loops.

"@descripttion: This is a header comment! @version: 1.0.0 @company: dcit-sh @author: Sunny Chen @Date: 2019-10-17 14:15:18 @lasteditors: Sunny Chen @LastEditTime: 2019-10-17 14:15:45 '''


class A(object) :
    pass


class B(A) :
    pass


class C(B) :
    def __new__(cls, *args, **kwargs) :
        return super().__new__(cls, *args, **kwargs)

        # Equivalent to:
        # return B.__new__(cls, *args,**kwargs)
        # return A.__new__(cls, *args,**kwargs)
        # return object.__new__(cls, *args,**kwargs)
Copy the code

2. In any new class__new__()Method, cannot call its own__new__()To create an instance, because it creates an endless loop.

class Bar(object) :
    def __new__(cls,*agrs,**kwagrs) :
        return Bar.__new__(Foo,*agrs,**kwagrs)
Copy the code

This will lead to failureBarCalling its own__new__()When the method creates an instance, it jumps to the second line for execution__new__()When it reaches the third line, it jumps to the second line__new__(), so the continuous will fall into an endless cycle.

3. Bar.__new__(Foo,*agrs,**kwagrs), which class to use(bar)__new__()Methods to make who(Foo)Instance object.


Typically, when a new class starts instantiating,__new__()Method returnsCLS (CLS refers to the current class), and then the class__init__()Method receives this instance as a constructor (i.eself) as its first argument, and then passed in one by one__new__ ()Method to receive positional and named parameters.

Note: if__new__()There is no returncls(that is, the current class), then of the current class__init__()Methods are not called. if__new__()Return an instance of another class (new or classic), and only the constructor of the returned class is called.

"@descripttion: This is a header comment! @version: 1.0.0 @company: dcit-sh @author: Sunny Chen @Date: 2019-10-17 15:56:23 @lasteditors: Sunny Chen @LastEditTime: 2019-10-17 15:56:23 '''


class Foo(object) :
    def __new__(cls, *args, **kwagrs) :
        return object.__new__(cls, *args, **kwagrs)

    def __init__(self, name) :
        self.name = name


class Bar(object) :
    def __new__(cls, *agrs, **kwagrs) :
        return object.__new__(Foo, *agrs, **kwagrs)


bar = Bar()
print(type(bar))  #foo is actually an instance of the Stranger class.


      
Copy the code

The above example will be found: manufactured isFooInstance object of.

Conclusion: So it can be described this way__new__ () and __ini__ ()In the new class__new__()The real instantiation method is to provide a shell for the class to create an instance frame, and then call the constructor within that frame__init__()Plump it up.

If you think about building a house,__new__()Methods Develop the site, lay the foundation, and store the raw materials on the site. while__init__()Methods To take materials from the site to build the building specified in the tender for the development of the site,__init__()Responsible for the detailed design, construction and fit-out of the building for delivery to the client.

Go and try it!


🎉 finally

  • For more references, see here:Chen Yongjia’s blog

  • Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!