• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python下singleton模式的实现方法

Python下singleton模式的实现方法

作者:shichen2014 字体:[增加 减小] 来源:互联网

shichen2014 通过本文主要向大家介绍了python singleton,singleton模式,java singleton模式,实现singleton模式,什么是singleton模式等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

很多开发人员在刚开始学Python 时,都考虑过像 c++ 那样来实现 singleton 模式,但后来会发现 c++ 是 c++,Python 是 Python,不能简单的进行模仿。

Python 中常见的方法是借助 global 变量,或者 class 变量来实现单件。本文就介绍以decorator来实现 singleton 模式的方法。示例代码如下:

##----------------------- code begin -----------------------

# -*- coding: utf-8 -*-
def singleton(cls):
"""Define a class with a singleton instance."""
instances = {}
def getinstance(*args, **kwds):
return instances.setdefault(cls, cls(*args, **kwds))
return getinstance
 
##1 未来版Python支持Class Decorator时可以这样用
class Foo(object):
def __init__(self, attr=1):
self.attr = attr

Foo = singleton( Foo ) ##2 2.5及之前版不支持Class Decorator时可以这样用

if __name__ == "__main__":
ins1 = Foo(2) # 等效于: ins1 = singleton(Foo)(2)
print "Foo(2) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins1), ins1.attr, ('error', 'ok')[ins1.attr == 2])
ins2 = Foo(3)
print "Foo(3) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins2), ins2.attr, ('error', 'ok')[ins2.attr == 2])
ins2.attr = 5
print "ins.attr=5 -> ins.attr=%d, %s" % (ins2.attr, ('error', 'ok')[ins2.attr == 5])
 
##------------------------ code end ------------------------

</div>

输出:

Foo(2) -> id(ins)=19295376, ins.attr=2, ok
Foo(3) -> id(ins)=19295376, ins.attr=2, ok
ins.attr=5 -> ins.attr=5, ok
</div> </div>

您可能想查找下面的文章:

  • Python下singleton模式的实现方法

相关文章

  • 简单使用Python自动生成文章
  • Python合并多个装饰器小技巧
  • 浅谈function(函数)中的动态参数
  • 简单掌握Python中glob模块查找文件路径的用法
  • 浅谈python中的getattr函数 hasattr函数
  • Python编程中使用Pillow来处理图像的基础教程
  • 实例讲解Python中的私有属性
  • Python多线程学习资料
  • 简单说明Python中的装饰器的用法
  • Python去除列表中重复元素的方法

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python中用于转换字母为小写的lower()方法使用简介
    • python数据结构树和二叉树简介
    • python打开网页和暂停实例
    • Python网页解析利器BeautifulSoup安装使用介绍
    • 详解Django框架中的视图级缓存
    • 在Python中操作字典之setdefault()方法的使用
    • Python转码问题的解决方法
    • Python写的Socks5协议代理服务器
    • python中字符串前面加r的作用
    • 利用python实现数据分析

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有