1. 程式人生 > >python singleton design pattern super()

python singleton design pattern super()

-s rpo 模塊 pri not tex __call__ turn http

python singleton design pattern

  1. decorate

  2. baseclass

  3. metaclass

  4. import module

  5. 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()