python - 单例模式
单例模式:
class Foo: instance = None def __init__(self,name): self.name = name @classmethod def get_instance(cls): #cls 类名 if cls.instance: return cls.instance else: obj = cls('google') cls.instance = obj return obj obj1 = Foo.get_instance() print(obj1) obj2 = Foo.get_instance() print(obj2)
out:
<__main__.Foo object at 0x00000000007D4278>
<__main__.Foo object at 0x00000000007D4278>
由上可知,obj1和obj2 内存地址都是一样的
UnixFBI 运维特工
www.unixfbi.com