单例模式(__new__):
class A:
__instance = None
def __init__(self, name):
self.name = name
# @classmethod
# def __new__(cls, *args, **kwargs):
# print("开始new新对象")
# # if not A.__new__(cls):
# # cls = A.__new__()
# return object.__new__(cls)
# @classmethod
# def get_instance(cls, name):
# if not cls.__instance:
# cls.__instance = A(name)
# return cls.__instance
@classmethod
def __new__(cls, name, *args, **kwargs):
if not cls.__instance:
cls.__instance = object.__new__(name)
return cls.__instance
def __str__(self):
return "name : %s"%self.name
a = A("zhangsan")
b = A("lisi")
print(a == b)
print(id(a))
print(id(b))