python singleton design pattern super()
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python singleton design pattern super()相关的知识,希望对你有一定的参考价值。
python singleton design pattern
-
decorate
-
baseclass
-
metaclass
-
import module
-
super()
一、A decorator
def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class MyClass(BaseClass): pass
当用MyClass() 去创建一个对象时这个对象将会是单例的。MyClass 本身已经是一个函数。不是一个类,所以你不能通过它来调用类的方法。所以对于
m=MyClass() n = MyClass() o=type(n)() m==n and m!=o and n != o 将会是True
二、baseclass
class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): # class_._instance = object.__new__(class_) 这行语句和下一行语句作用一样的 class_._instance=super(Singleton,class_).__new__(class_) return class_._instance class MyClass(Singleton): def __init__(self,name): self.name = name print(name)
pros
是真的类
cons:
在多继承的时候要注意
三、metaclass
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] #Python2 class MyClass(BaseClass): __metaclass__ = Singleton #Python3 class MyClass(BaseClass, metaclass=Singleton): pass
Pros
- It‘s a true class
- Auto-magically covers inheritance
- Uses
__metaclass__
for its proper purpose (and made me aware of it)
四、通过导入模块
五、
super(type[,object or type])
If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type)
must be true.
If the second argument is a type, issubclass(type2, type)
must be true (this is useful for classmethods).
note :super() 只能用于新式类
链接 https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
以上是关于python singleton design pattern super()的主要内容,如果未能解决你的问题,请参考以下文章
[Design Pattern] Singleton Pattern 简单案例
如何使用Singleton Design Pattern java连接到SQL数据库?
从壹开始 [ Design Pattern ] 之二 ║ 单例模式 与 Singleton