1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
>>> class SingleTon(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = object.__new__(cls, *args, *kwargs) return cls._instance
>>> class TestClass(SingleTon): a = 1
>>> test1 = TestClass() >>> test2 = TestClass() >>> print(test1.a, test2.a) 1 1 >>> test1.a = 2 >>> print(test1.a, test2.a) 2 2 >>> print(id(test1), id(test2)) 140666831839864 140666831839864
>>> def SingleTon(cls, *args, **kwargs): instances = {} def _singleton(): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return _singleton
>>> @SingleTon class LastClass(object): a = 1
>>> test1 = LastClass() >>> test2 = LastClass() >>> print(test1.a, test2.a) 1 1 >>> print(id(test1), id(test2)) 140666831841376 140666831841376
>>> class SignalTon(object): _state = {} def __new__(cls, *args, **kwargs): obj = object.__new__(cls, *args, **kwargs) obj.__dict__ = cls._state return obj
>>> class TestClass(SignalTon): a = 1 >>> test1 = TestClass() >>> test2 = TestClass() >>> test1.a = 2 >>> print(test1.a, test2.a) 2 2
|