Python设计模式之单例模式实例
注:使用的是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是一个类方法,会创建对象时调用。而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'

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

PHP和Python各有优劣,选择取决于项目需求和个人偏好。1.PHP适合快速开发和维护大型Web应用。2.Python在数据科学和机器学习领域占据主导地位。

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Docker利用Linux内核特性,提供高效、隔离的应用运行环境。其工作原理如下:1. 镜像作为只读模板,包含运行应用所需的一切;2. 联合文件系统(UnionFS)层叠多个文件系统,只存储差异部分,节省空间并加快速度;3. 守护进程管理镜像和容器,客户端用于交互;4. Namespaces和cgroups实现容器隔离和资源限制;5. 多种网络模式支持容器互联。理解这些核心概念,才能更好地利用Docker。

在 VS Code 中,可以通过以下步骤在终端运行程序:准备代码和打开集成终端确保代码目录与终端工作目录一致根据编程语言选择运行命令(如 Python 的 python your_file_name.py)检查是否成功运行并解决错误利用调试器提升调试效率

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

VS Code 全称 Visual Studio Code,是一个由微软开发的免费开源跨平台代码编辑器和开发环境。它支持广泛的编程语言,提供语法高亮、代码自动补全、代码片段和智能提示等功能以提高开发效率。通过丰富的扩展生态系统,用户可以针对特定需求和语言添加扩展程序,例如调试器、代码格式化工具和 Git 集成。VS Code 还包含直观的调试器,有助于快速查找和解决代码中的 bug。

VS Code 扩展存在恶意风险,例如隐藏恶意代码、利用漏洞、伪装成合法扩展。识别恶意扩展的方法包括:检查发布者、阅读评论、检查代码、谨慎安装。安全措施还包括:安全意识、良好习惯、定期更新和杀毒软件。

CentOS 安装 Nginx 需要遵循以下步骤:安装依赖包,如开发工具、pcre-devel 和 openssl-devel。下载 Nginx 源码包,解压后编译安装,并指定安装路径为 /usr/local/nginx。创建 Nginx 用户和用户组,并设置权限。修改配置文件 nginx.conf,配置监听端口和域名/IP 地址。启动 Nginx 服务。需要注意常见的错误,如依赖问题、端口冲突和配置文件错误。性能优化需要根据具体情况调整,如开启缓存和调整 worker 进程数量。
