__init__ and __new__

__init__和__new__

I have been naive to think that understanding the python's __init__()method is equivalent to recognize the class constructor, results, __new__()methods suddenly appeared in front of me, I suddenly realize that the original __new__is the boss. Why do you say?
We have from the first __new__(cls[,...])parameter, said talking about, __new__first argument is the class, and all the rest of the parameters passed to the call after a successful __init__method initializes, it could easily see who is the father of the boy who is the relationship .

Therefore, the __new__method (first execution) before the __init__method executes:

class A:
    pass


class B(A):
    def __new__(cls):
        print("__new__方法被执行")
        return super().__new__(cls)

    def __init__(self):
        print("__init__方法被执行")


b = B()
__new__方法被执行
__init__方法被执行

We compared the parameters of the two methods can be found __new__is to pass class (cls), and __init__instantiate an object method passed in class (self), but interestingly, __new__the value returned is an instance of an object (ps: if __new__method returns None, the __init__method will not be executed, and the return value in the parent class can only call the __new__method, and the class can not call unrelated __new__method). So we can understand the relationship between them __new__is the open borders of major general, and __init__is working hard on this piece of territory of small people, only __new__after the implementation, after a good open territory, __init__to work.
In most cases, we do not need to rewrite their own __new__methods, but when inherited type (eg class str, int etc.) an immutable, it features on the utmost importance. We cite the following example:

class CapStr(str):
    def __init__(self, string):
        string = string.upper()


a = CapStr("I love China!")
print(a)
I love China!
class CapStr(str):
    def __new__(cls, string):
        string = string.upper()
        return super().__new__(cls, string)


a = CapStr("I love China!")
print(a)
I LOVE CHINA!

According to the above theory we can do the analysis, we know that strings are immutable, so the first example, the string passed the equivalent of territory has been laid, but this piece of territory in addition to other generals who can not change , __init__you can only look on in despair over this territory, when this territory is "I love China!". The second example, a __new__major general again to open up a piece of territory, so the contents of the territory has changed, then this territory became "I LOVE CHINA!".

Summary: __new__and __init__wanted to fit in real python is the class constructor.

Guess you like

Origin www.cnblogs.com/Dr-wei/p/11851423.html