当实例化一个类时,首先调用__new__()来创建类的实例,然后调用__init__()来初始化实例。
__new__ ():
调用它来创建类cls. ...的新实例
如果在对象构造期间调用__new__(),它返回一个
实例,则新实例的__init__()方法将为
像__init__(self[,…])一样调用,…
__init__ ():
在实例创建后调用(通过__new__()),…
因为__new__()和__init__()在构造对象时一起工作
(__new__()来创建它,__init__()来定制它),…
例如,在实例化Teacher类时,首先调用__new__()来创建Teacher类的实例,然后调用__init__()来初始化实例,如下所示:
class Teacher:
def __init__(self, name):
self.name = name
class Student:
def __init__(self, name):
self.name = name
obj = Teacher("John") # Instantiation
print(obj.name)
输出如下:
<class '__main__.Teacher'>
John
并且,使用Teacher类实例的__new__(),我们可以创建Student类的实例,如下所示:
# ...
obj = Teacher("John")
print(type(obj))
print(obj.name)
obj = obj.__new__(Student) # Creates the instance of "Student" class
print(type(obj))
现在,创建了Student类的实例,如下所示:
<class '__main__.Teacher'>
<__main__.Teacher object at 0x7f4e3950bf10>
<class '__main__.Student'> # Here
接下来,如果我们尝试从Student类的**实例中获取name变量的值,如下所示:
obj = Teacher("John")
print(type(obj))
print(obj.name)
obj = obj.__new__(Student)
print(type(obj))
print(obj.name) # Tries to get the value of "name" variable
发生以下错误是因为Student类的实例还没有被__init__()初始化:
AttributeError: 'Student'对象没有属性'name'
因此,我们初始化Student类的实例,如下所示:
obj = Teacher("John")
print(type(obj))
print(obj.name)
obj = obj.__new__(Student)
print(type(obj))
obj.__init__("Tom") # Initializes the instance of "Student" class
print(obj.name)
然后,我们可以从Student类的实例中获取name变量的值,如下所示:
<class '__main__.Teacher'>
John
<class '__main__.Student'>
Tom # Here