Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。

#foo1.py
class Singleton(object):
    def foo(self):
        pass
singleton = Singleton()


#foo.py
from foo1 import singleton

直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象

 

二、静态变量方法

先执行了类的__new__方法(我们没写时,默认调用object.__new__),实例化对象;然后再执行类的__init__方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式。

class Singleton(object):
    def __new__(cls,a):
        if not hasattr(cls, '_instance'):
            cls._instance = object.__new__(cls)
        return cls._instance
    def __init__(self,a):
        self.a = a
    def aa(self):
        print(self.a)


a = Singleton("a")

变种:利用类的静态方法或者类方法,实现对函数初始化的控制。该方法需要手动调用静态方法实现实例。本质上是手动版的__new__方法。

class Singleton:
    @staticmethod
    def instance1(*args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            Singleton._instance = Singleton(*args, **kwargs)
        return Singleton._instance

  
    @classmethod
    def instance2(cls,*args, **kwargs):
        if not hasattr(cls, "_instance"):
            Singleton._instance = Singleton(*args, **kwargs)
        return Singleton._instance


a = Singleton.instance1() 
b = Singleton.instance2() 
print(a == b)
手动版静态版

相关文章:

  • 2022-02-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-28
  • 2021-12-23
相关资源
相似解决方案