Monday, April 2, 2012

如何在Python內使用Singleton方法



# There is an example to do with Singleton in Python def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class MyClass(): def __init__(self): self.data = "AAA" if __name__ == "__main__": obj_a = MyClass() obj_a.data = "AAAA" print obj_a, obj_a.data obj_b = MyClass() print obj_b, obj_b.data

No comments: