## _instance一定不要两个下划线,否则这种方式取不到属性
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kwargs)
return cls._instance
class Myclass(Singleton):
a = 1
class Borg(object):
_state = {}
def __new__(cls, *args, **kwargs):
ob = super(Borg, cls).__new__(cls, *args, **kwargs)
ob.__dict__ = cls._state
return ob
class Myclass2(Borg):
a = 1
def singleton(cls, *args, **kwargs):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return getinstance
14.python单例模式
猜你喜欢
转载自blog.csdn.net/gold_time_/article/details/80959936
今日推荐
周排行