class Singleton(object):
def __new__(cls, *args, **kargv):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kargv)
return cls._instance
class MyTestClass1(Singleton):
a = 1
def singleton(cls, *argc, **kargv):
instance = {}
def _singleton():
if cls not in instance:
instance[cls] = cls(*argc, **kargv)
return instance[cls]
return _singleton
@singleton
class MyTestClass2(object):
a = 1
def __init__(self):
self.x = None
if __name__ == "__main__":
one = MyTestClass1()
two = MyTestClass1()
two.a = 2
print (one.a)
one = MyTestClass2()
two = MyTestClass2()
two.a = 3
print (one.a)
转载于:https://my.oschina.net/u/1450570/blog/412095