To be a better coder
分类: LINUX
2019-03-06 13:45:58
作为Python模块时是天然的单例模式 #创建一个sington.py文件, 内容如下 class Singleton(object): def foo(self): pass mysington = Singleton() # 运用 from sington import mysington mysington.foo()
1 >>> #普通模式 2 ... class A(object): 3 ... def __init__(self,name,male): 4 ... self.name = name 5 ... self.name = male 6 ... 7 >>> #实例化多个对象 8 ... obj1 = A('ben','boy') 9 >>> obj2 = A('min','girl') 10 >>> obj3 = A('miao','boy') 11 >>> ##打印内存地址,可以看到内存地址都是不一样的 12 ... print id(obj1),id(obj2),id(obj3) 13 140230687882448 140230687882512 140230687882576 14 >>> 15 >>> #单例模式 16 ... class A(object): 17 ... __instance = None 18 ... def __init__(self,name,male): 19 ... self.name = name 20 ... self.name = male 21 ... @staticmethod 22 ... def create_obj(): 23 ... if not A.__instance: 24 ... A.__instance = A('ben','boy') 25 ... return A.__instance 26 ... else: 27 ... return A.__instance 28 ... 29 >>> #单例模式实例化多个对象 30 ... obj1 = A.create_obj() 31 >>> obj2 = A.create_obj() 32 >>> obj3 = A.create_obj() 33 >>> ##打印内存地址,可以看到内存地址都是一样的 34 ... print id(obj1),id(obj2),id(obj3) 35 140230687882832 140230687882832 140230687882832 36 >>>