Python __init__练习

'''
#使用场景:想让p1和p2......的内存空间地址是一个。
class Person(object):
instance = None

def __new__(cls, *args, **kwargs):
print("__new__方法执行")
if not cls.instance:
cls.instance = super().__new__(cls)
return cls.instance #将空间内存地址(返回值)返回解释器,赋值给__init__里的self。

def __init__(self, name, age):
print("__init__方法执行", id(self))
self.name = name
self.age = age


p1 = Person("huchangxi", 22)
p2 = Person("huchangxi", 22)
print(id(p1)) # 1903008709072
print(id(p2)) # 1903008709072
'''
posted @ 2022-04-19 23:35  呼长喜  阅读(24)  评论(0编辑  收藏  举报