__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.