Python设计模式之单例模式实例
发布时间:2023-06-02 12:43:02
注:使用的是Python 2.7。
一个简单实现
class Foo(object):
__instance = None
def __init__(self):
pass
@classmethod
def getinstance(cls):
if(cls.__instance == None):
cls.__instance = Foo()
return cls.__instance
if __name__ == '__main__':
foo1 = Foo.getinstance()
foo2 = Foo.getinstance()
print id(foo1)
print id(foo2)
print id(Foo())
输出的前两个结果是相同的(id(foo1)与id(foo2)的值相同),第三个结果和前两个不同。这里类方法getinstance()用于获取单例,但是类本身也可以实例化,这样的方式其实并不符合单例模式的要求。但是这样做也有好处,代码简单,大家约定好这样子调用就行了。但是最好在类的命名上也体现了出来这是一个单例类,例如Foo_singleton。
换一个思路
先说一下init和new的区别:
class Foo(object):
__instance = None
def __init__(self):
print 'init'
if __name__ == '__main__':
foo = Foo()
运行结果是:
init
而下面的示例:
class Foo(object):
__instance = None
def __init__(self):
print 'init'
def __new__(cls, *args, **kwargs):
print 'new'
if __name__ == '__main__':
foo = Foo()
运行结果是:
new
new是一个类方法,会创建对象时调用。而init方法是在创建完对象后调用,对当前对象的实例做一些一些初始化,无返回值。如果重写了new而在new里面没有调用init或者没有返回实例,那么init将不起作用。以下内容引用自http://docs.python.org/2/reference/datamodel.html#object.new
If __new__() returns an instance of cls, then the new instance's __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().
If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.
这样做:
class Foo(object):
__instance = None
def __init__(self):
print 'init'
def __new__(cls, *args, **kwargs):
print 'new'
if cls.__instance == None:
cls.__instance = cls.__new__(cls, *args, **kwargs)
return cls.__instance
if __name__ == '__main__':
foo = Foo()
错误如下:
RuntimeError: maximum recursion depth exceeded in cmp
而这样也有一样的错误:
class Foo(object):
__instance = None
def __init__(self):
if self.__class__.__instance == None:
self.__class__.__instance = Foo()
print 'init'
if __name__ == '__main__':
foo = Foo()
该怎么做呢?
下面参考了http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python/31887#31887:
class Foo(object):
__instance = None
def __new__(cls, *args, **kwargs):
print 'hhhhhhhhh'
if not cls.__instance:
cls.__instance = super(Foo, cls).__new__(cls, *args, **kwargs)
return cls.__instance
def hi(self):
print 'hi, world'
print 'hi, letian'
if __name__ == '__main__':
foo1 = Foo()
foo2 = Foo()
print id(foo1)
print id(foo2)
print isinstance(foo1, object)
print isinstance(foo1, Foo)
foo1.hi()
运行结果:
hhhhhhhhh
hhhhhhhhh
39578896
39578896
True
True
hi, world
hi, letian
那么,到底发生了什么,我们先回顾一下super:
>>> print super.__doc__
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
可以肯定上面的单例模式代码中的这一行代码:
cls.__instance = super(Foo, cls).__new__(cls, *args, **kwargs)
super(Foo, cls)是object,super(Foo, cls).new方法使用的是object的new方法。我们看一下object.new方法的作用:
>>> print object.__new__.__doc__
T.__new__(S, ...) -> a new object with type S, a subtype of T
如果是一个继承链
class Fo(object):
def __new__(cls, *args, **kwargs):
print 'hi, i am Fo'
return super(Fo, cls).__new__(cls, *args, **kwargs)
class Foo(Fo):
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
print Foo is cls
print issubclass(cls, Fo)
print issubclass(cls, object)
cls.__instance = super(Foo, cls).__new__(cls, *args, **kwargs)
return cls.__instance
def hi(self):
print 'hi, world'
if __name__ == '__main__':
foo1 = Foo()
foo1.hi()
print isinstance(foo1, Foo)
print isinstance(foo1, Fo)
print isinstance(foo1, object)
运行结果如下:
True
True
True
hi, i am Fo
hi, world
True
True
True
如果如下定义Fo,也正常运行:
class Fo(object):
pass
但是,若这样定义:
class Fo(object):
def __new__(cls, *args, **kwargs):
print 'hi, i am Fo'
运行时报错如下:
AttributeError: 'NoneType' object has no attribute 'hi'


猜你喜欢
- torch.nn.Conv2d中自定义权重torch.nn.Conv2d函数调用后会自动初始化weight和bias,本文主要涉及如何自定义
- 前戏有时候生产环境是以项目来命名,有时候会出现更名情况,其实如何安全的更改数据库名,是个非常棘手的问题,特别是针对 MySQL 来数据库来说
- 如下所示:import pandas as pddef my_min(a, b): return min(abs(a),abs(
- 什么是Dynamic HTML 今天我们以问答的形式来讲述什麽是Dynamic Html。问:亲爱的网猴,我经常看到讲述有关“Dynamic
- 据国外媒体报道,相较于IE8浏览器,微软最新一代浏览器IE9的最大改进就是硬件加速HTML5。微软承诺,通过利用IE9中的硬件加速功能,开发
- import datetime as dtdef log_time(message, time=None): if time i
- Python 相对路径报错:"No such file or directory"'原因及解决方法如果你取相对路
- 本文实例为大家分享了python实现12306图片验证效果的具体代码,供大家参考,具体内容如下思路:在鼠标点击位置加一个按钮,然后再按钮中的
- 目录技术背景diagrams的安装基础逻辑关系图组件簇的定义总结概要技术背景对于一个架构师或者任何一个软件工程师而言,绘制架构图都是一个比较
- 1、层次索引1.1 定义在某一个方向拥有多个(两个及两个以上)索引级别,就叫做层次索引。通过层次化索引,pandas能够以较低维度形式处理高
- 一、什么是框架框架的本质就是一个socket服务,可以完成不同主机之间的通信。它是一个半成品的项目,其中可能已经封装好了基本的功能,比如路由
- 最近学了一个关于省市级联简单的小例子,贴出来与大家分享一下:<!DOCTYPE html><html lang="
- 简介:with是从Python2.5引入的一个新的语法,它是一种上下文管理协议,目的在于从流程图中把 try,except 和finally
- 前言:我们平常会使用很多社交媒体,如微信、微博、抖音等等,在这些平台上面,我们会关注某些KOL,同时自己身边的亲朋好友也会来关注我们,成为我
- Python中sorted()用法sorted() 作为 Python 内置函数之一,其功能是对序列(列表、元组、字典、
- 本文介绍了多个 Python IDE,并评价其优缺点。读者可以参考此文列举的 Python IDE 列表,选择适合自己的编辑器。写 Pyth
- PyQt5信号与槽高级自定义信号与槽所谓高级自定义信号与槽,指的就是我们可以以自己喜欢的方式定义信号与槽函数,并传递参数,自定义信号的一般流
- 代码是这样的:var reg = /^1[345678][0-9]{9}$/g;console.log(reg.test(153280446
- 要是XHTML与CSS能面向对象。。太阳应该从北边升起了。但是,凡事都应该带着OO的思想来看问题,也勉强可以凑数拉。其实,早在零几年就有人提
- 摘要:Read Committed事务运行期间,只要别的事务修改数据并提交,即可读到人家修改的数据,所以会有不可重复读、幻读问题。ReadV