标签:python2 singleton tar color pass use code blog 方法
一、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:
在多继承的时候要注意
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
__metaclass__
for its proper purpose (and made me aware of it)
五、
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()
标签:python2 singleton tar color pass use code blog 方法
原文地址:http://www.cnblogs.com/yuyang26/p/7717571.html