class Foo(object): instance = None def __init__(self): pass def process(self): return '1234565' @classmethod #版本1单例模式 def get_instance(cls): if Foo.instance: return Foo.instance else: Foo.instance = Foo() return Foo.instance obj1 = Foo() print(obj1.process()) obj2 = Foo() print(obj2.process()) obj1不相等obj2 id(obj1) obj1 = Foo.get_instance() obj2 = Foo.get_instance() 此时的obj1=obj2 class Foo(object): instance = None def __init__(self): self.name = 'alex' def __new__(cls, *args, **kwargs): if Foo.instance: return Foo.instance else: obj = object.__new__(cls, *args, **kwargs) #创建对象的本质是new new先执行 return return obj obj1 = Foo() obj2 = Foo() print(id(obj1), id(obj2)) obj1=obj2 单例模式2 高级版 永远用一个对象的实例! 创建的对象内部封装的值是一样的 就搞成单例模式