注:先调用__new__方法,后通过__init__初始化。
class Char(object):
__instance = None
__flag = None
def __new__(cls, name):
if cls.__instance == None:
cls.__instance = object.__new__(cls)
return cls.__instance
else:
return cls.__instance
def __init__(self, name):
if Char.__flag == None:
self.name = name
Char.__flag = self.name
a = Char("A")
print(id(a))
b = Char("B")
print(id(b))
print(b.name)