码迷,mamicode.com
首页 > 编程语言 > 详细

python singleton design pattern super()

时间:2017-10-23 18:35:25      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:python2   singleton   tar   color   pass   use   code   blog   方法   

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

标签:python2   singleton   tar   color   pass   use   code   blog   方法   

原文地址:http://www.cnblogs.com/yuyang26/p/7717571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!