Python Implementation Singleton mode
# using Python to implement a singleton pattern # method: using the __new__ method Class singleton (object): def __new__ (Cls, *args, **kwargs): if not hasattr (cls, ' _instance '): cls._instance = object.__new__ (Cls, *args, **kwargs) return cls._instanceclass testclass (SingleTon): a = 1# Method Two: using adorners (decorator) def singleton1 (Cls, *args, **kwargs): Instances = {} def _singleton (): if cls not in instances: instances[cls] = cls (*args, **kwargs) return instAnces[cls] return _singleton@singleton1class testclass1 (object): a = 1# Shared Properties properties are shared, but not singleton mode Class singleton3 (object): _state = {} def __new__ (Cls, *args, **kwargs): obj = object.__new__ (Cls, *args, **kwargs) obj.__dict__ = cls._state     RETURN OBJCLASS TESTCLASS3 (SingleTon3): a =  1TEST1 = TESTCLASS3 () TEST2 = TESTCLASS3 () test1.a = 2print (test1.a) print ( test2.a) print (test1) print (test2)
This article is from the "Xu Big Tree" blog, please be sure to keep this source http://abelxu.blog.51cto.com/9909959/1967293
Python Implementation Singleton mode