单例模式
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kwargs)
rerurn cls._instance
class A(Singleton):
pass
# 类A即为单例类
# 创建实例时把所有实例的__dict__指向同一个字典,这样它们都具有相同的属性和方法(类的__dict__存储对象属性)
class Singleton(object):
_state = {}
def __new__(cls, *args, **kwargs):
ob = super(Singleton,cls).__new__(cls, *args, **kwargs)
ob.__dict__ = cls._state
return ob
class B(Singleton):
pass
# 类B即为单例类
def singleton(cls):
instance = {}
def wapper():
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return wapper
@singleton
class C:
pass
# 类C即为单例类
# 作为Python模块时是天然的单例模式
#创建一个sington.py文件,内容如下:
class Singleton(object):
def foo(self):
pass
mysington = Singleton()
# 运用
from sington import mysington
mysington.foo()