美文网首页
Python 单例模式

Python 单例模式

作者: 陈忠俊 | 来源:发表于2020-08-25 21:27 被阅读0次

元类方法__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之理解单例模式

    python之理解单例模式 1、单例模式 单例模式(Singleton Pattern)是一种常见的软件设计模式,...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 2018-06-19 Python中的单例模式的几种实现方式的及

    转载自: Python中的单例模式的几种实现方式的及优化 单例模式 单例模式(Singleton Pattern)...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 基础-单例模式

    单例模式总结-Python实现 面试里每次问设计模式,必问单例模式 来自《Python设计模式》(第2版) 1.理...

  • python单例模式

    python单例模式实现方式 使用模板 python模块是天然的单例模式(.pyc文件的存在) 使用__new__...

  • 一套完整Python经典面试题,实力派,做内容不做标题党!

    文末含Python学习资料 1:Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例...

  • Python 面向对象7: 单例模式

    一、内容 1.1、单例设计模式 1.2、__new__方法 1.3、Python 中的单例 二、单例设计模式 2....

  • Python设计模式 之 Borg模式

    Borg模式 是单例模式在python中的变种。传统单例模式在python中,存在继承兄弟类之间状态隔离的问题。 ...

网友评论

      本文标题:Python 单例模式

      本文链接:https://www.haomeiwen.com/subject/bsftsktx.html