#单例模式#装饰器版本def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance@singletonclass Myclass: passins1 = Myclass()ins2 = Myclass()print(id(ins1),id(ins2))#43877264 43877264#import方法 --> 天然的单例模式#mysingleton.py 一个py文件class My_Singleton(object): def foo(self): passmy_singleton = My_Singleton()#to use from mysingleton# import my_singleton 在另外一个文件中导入类的实例对象my_singleton.foo()#使用__new__方法class Singleton(object): def __new__(cls): if not hasattr(cls,'_instance'): orig = super(Singleton,cls) cls._instance = orig.__new__(cls) return cls._instance# class MyClass(singleton):# a = 1ins3 = Singleton()ins4 = Singleton()print(id(ins3),id(ins4))#43877656 43877656