Python 单例模式

元类方法__call__ 可以这样使用:

class TestCall:
    def __init__(self, value):
        self.value = value
    def __call__(self, value = None):
        if value is None:
            print("value is: ", self.value)
        else:
            self.value = value

如下:

>>> test = TestCall(7.7)
>>> test.value
7.7
>>> test()
value is:  7.7
>>> test(20200707)
>>> test.value
20200707
>>> test()
value is:  20200707
>>>

调用__call__实现python 单例模式

class SingleInstance(type):
    instance = None
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
    def __call__(self, *args, **kwargs):
        if self.instance is None:
            self.instance = super().__call__(*args, **kwargs)
            return self.instance
        else:
            return self.instance

元类继承:

class TestSingleInstance(metaclass = SingleInstance):
    def __init__(self):
        print("Testing start...")

测试:

>>> my_instance = TestSingleInstance()
Testing start...
>>> my_instance2 = TestSingleInstance()
>>> my_instance is my_instance2
True
>>> my_instance3 = TestSingleInstance()
>>> my_instance3 is my_instance
True
>>>

你可能感兴趣的:(Python 单例模式)