单例模式:

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 内存地址都是一样的

相关文章:

  • 2021-06-11
  • 2021-12-25
  • 2022-03-02
  • 2021-05-23
猜你喜欢
  • 2021-12-14
  • 2022-03-03
  • 2021-05-22
  • 2022-03-01
相关资源
相似解决方案