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/

多继承,在python3 中全部都是新式类

新式类的继承顺序是广度优先,python2 中的经典类是深度优先

通过一个例子来理解

class A(object):
def f1(self):
print('a.f1') class B(A):
def f2(self):
print('b.f1') class F(object):
def f1(self):
print('f.f1') class C(B,F):
def f3(self):
print('c.f1') insta = C()
insta.f1()

关系图

将会打印出a.f1

如果代码改为

class A(object):
def f1(self):
print('a.f1') class B(A):
def f2(self):
print('b.f1') class F(A):
def f1(self):
print('f.f1') class C(B,F):
def f3(self):
print('c.f1') insta = C()
insta.f1()

关系图如下:

运行结果是f.f1


python 2 代码如下

class A:  #经典类
    def foo(self):
        print'A'
class B(A):     def foo(self):
        print'B'
class C(A):
    pass
    #def foo(self):
     #   print'C'
class D(B):
    #def foo(self):
     #   print 'D'
    pass class F(B):
    #pass
    def foo(self):
        print 'F'
        pass class G(D,F):
    pass
g1=G()
g1.foo() #打印出 B


python 3 代码

class A(object):
def f1(self):
print('a.f1') class B(A):
pass
def f1(self):
print('b.f1') class C(A):
def f1(self):
print('c.f1') class D(B):
pass
# def f1(self):
# print('D.f1') class F(B):
pass
def f1(self):
print('f.f1') class G(D,F):
# def f1(self):
# print('g.f1')
pass insta = G()
insta.f1() #打印出f.f1

python singleton design pattern super() 多继承的更多相关文章

  1. Singleton Design Pattern

    The Singleton pattern is one of the simplest design patterns, which restricts the instantiation of a ...

  2. Design Principle vs Design Pattern 设计原则 vs 设计模式

    Design Principle vs Design Pattern设计原则 vs 设计模式 来源:https://www.tutorialsteacher.com/articles/differen ...

  3. Null Object Design Pattern (Python recipe)

    Null Object 个人感觉非常有用.也是在review公司其他同事写代码的时候看到. 当时使用了flask的request全局请求变量g,然后使用了g.x保存了一个东西. 当时在view代码读取 ...

  4. Design Pattern —— Singleton

    Design Pattern —— Singleton   强力推荐枚举和类级内部类方式实现单例模式 单例模式是开发中非常常用的一种模式,简单的说,我们希望一个类永远都只有一个对象. 主要有两个用途: ...

  5. [Design Pattern] Singleton Pattern 简单案例

    Singleton Pattern, 即单例模式,用于获取类的一个对象,该对象在整个应用中是其类的唯一对象.单例模式属于创建类的设计模式. SingleObject 作为单例类,内含了一个静态私有的 ...

  6. 关于Python中的类普通继承与super函数继承

    关于Python中的类普通继承与super函数继承 1.super只能用于新式类 2.多重继承super可以保公共父类仅被执行一次 一.首先看下普通继承的写法 二.再看看super继承的写法 参考链接 ...

  7. 说说设计模式~大话目录(Design Pattern)

    回到占占推荐博客索引 设计模式(Design pattern)与其它知识不同,它没有华丽的外表,没有吸引人的工具去实现,它是一种心法,一种内功,如果你希望在软件开发领域有一种新的突破,一个质的飞越,那 ...

  8. 设计模式(Design Pattern)系列之.NET专题

    最近,不是特别忙,重新翻了下设计模式,特地在此记录一下.会不定期更新本系列专题文章. 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结. 使用 ...

  9. [转]Design Pattern Interview Questions - Part 4

    Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...

随机推荐

  1. linux 升级 5.0.2内核

    1.下载 wet https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.0.2.tar.xz -o /usr/src/ cd /usr/src ta ...

  2. spring 配置 线程池并使用 springtest 进行测试

    在 applicationContext.xml 中配置spring线程池: <!-- 包路径扫描 --> <context:component-scan base-package= ...

  3. mybatis源码-解析配置文件(二)之解析的流程

    目录 1. 简介 2. 配置文件解析流程分析 2.1 调用 2.2 解析的目的 2.3 XML 解析流程 2.3.1 build(parser) 2.3.2 new XMLConfigBuilder( ...

  4. 软件工程第三次作业(One who wants to wear the crown, Bears the crown.)

    最大连续子数组和 题目 给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],-,a[n],求该序列如a[i]+a[i+1]+-+a[j]的子段和的最大值.当所给的整数均为负数时定义子段和 ...

  5. 一个web应用的诞生(3)--美化一下

    经过上一章的内容,其实就页面层来说已结可以很轻松的实现功能了,但是很明显美观上还有很大的欠缺,现在有一些很好的前端css框架,如AmazeUI,腾讯的WeUI等等,这里推荐一个和flask集成很好的b ...

  6. 阿里云rds 备份和还原

    阿里云rds 备份和还原 转发:https://www.cnblogs.com/lin1/p/8617764.html 转发:https://help.aliyun.com/knowledge_det ...

  7. TKmath Package gp数据类型

    点,向量,方向 二维:gp_Pnt2d, gp_Vec2d, gp_Dir2d:它们的内部都存储 gp_XY 三维:gp_Pnt, gp_Vec, gp_Dir:它们的内部都存储 gp_XYZ 轴向与 ...

  8. (转)Unity内建图标列表

    用法 Gizmos.DrawIcon(transform.position, "PointLight Gizmo"); UnityEditor.EditorGUIUtility.F ...

  9. 七个要素帮你打造现象级手游!优化程度堪比《QQ飞车》

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由WeTest质量开放平台团队发表于云+社区专栏 作者:申江涛,腾讯互娱客户端工程师 商业转载请联系腾讯WeTest获得授权,非商业转载 ...

  10. 英国诗人乔叟Dethe is my Finaunce金融

    英国诗人乔叟Dethe is my Finaunce金融 英语中“金融”在14世纪,金融计算时间价值的手段.就随机结果签约的能力.一个允许转让金融权后的清算.<Lamentation of Ma ...