new在前去创建对象,init在后对对象的实例属性进行赋值,最后将创建的对象放在p1(本代码的实例化对象)中。
"""
__init__和__new__
__new__:创建对象。
__init__:对创建的对象进行初始化。
"""
#定义Person类
class Person(object):
def __new__(cls, *args, **kwargs):
print("__new__()方法被调用,函数中cls的id为:{0}".format(id(cls)))
obj = super().__new__(cls)
print("创建的obj对象的id为:{0}".format(id(obj)))
return obj
def __init__(self, name, age):
print("__init__()被调用,函数中self的id为:{0}".format(id(self)))
self.name = name
self.age = age
print("object类对象的id为:{0}".format(id(object)))
print("Person类对象的id为:{0}".format(id(Person)))
#创建Person类的实例对象
p1 = Person("张三", 20)
print("p1这个Person类对象的id为:{0}".format(id(p1)))
附一张内在逻辑的导向图:实例化Person时,先将Person给到new方法当中的cls,然后将cls传到object方法的new方法去创建对象,其后将创建的对象赋值给self,self初始化结束后,将对象赋值给p1。