Example 1:
class A(object):
def __init__(self):
print("这是 init 方法")
def __new__(cls):
print("这是 new 方法")
return object.__new__(cls)
A()
print:
[root@localhost demo01]# python3 text20210116.py
这是 new 方法
这是 init 方法
to sum up:
- __new__ must have at least one parameter cls, which represents the class to be instantiated. This parameter is automatically provided by the Python interpreter during instantiation.
- __new__ must have a return value to return the instantiated instance. This point must be paid special attention to when implementing __new__ by yourself. You can return an instance from the parent class __new__, or directly an instance from object's __new__ .
- __init__ has a parameter self, which is the instance returned by this __new__. __init__ can complete some other initialization actions on the basis of __new__, and __init__ does not require a return value.
- We can compare it to a manufacturer. The __new__ method is the initial purchase of raw materials, and the __init__ method is to process and initialize the goods on the basis of raw materials.
Example two:
class A(object):
def __init__(self):
print(self)
print("这是 init 方法")
def __new__(cls):
print(id(cls))
print("这是 new 方法")
ret = object.__new__(cls)
print(ret)
return ret
print(id(A))
A()
print:
[root@localhost demo01]# python3 text20210116.py
43020808
43020808
这是 new 方法
<__main__.A object at 0x7fcf5938bcc0>
<__main__.A object at 0x7fcf5938bcc0>
这是 init 方法