#使用__metaclass__(元类)的高级python用法
class Singleton2(type):
def __init__(cls, name, bases, dict):
super(Singleton2, cls).__init__(name, bases, dict)
cls._instance = None
def __call__(cls, *args, **kw):
if cls._instance is None:
cls._instance = super(Singleton2, cls).__call__(*args, **kw)
return cls._instance class MyClass3(object):
__metaclass__ = Singleton2 one = MyClass3()
two = MyClass3() two.a =
print one.a
#
print id(one)
#
print id(two)
#
print one == two
#True
print one is two #True #使用装饰器(decorator),
#这是一种更pythonic,更elegant的方法,
#单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的
def singleton(cls, *args, **kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton @singleton
class MyClass4(object):
a =
def __init__(self, x=):
self.x = x one = MyClass4()
two = MyClass4() two.a =
print one.a
#
print id(one)
#
print id(two)
#
print one == two
#True
print one is two
#True
one.x =
print one.x
#
print two.x
#

本文转载自:python黑洞网

最新文章

  1. 【原创】开源.NET排列组合组件KwCombinatorics使用(二)——排列生成
  2. 安装过程中出现PKG_CONFIG_PATH的问题解决方法
  3. 二进制打印与逆序_C语言(转)
  4. tcp MSL
  5. C#中的线程(上)-入门 分类: C# 线程 2015-03-09 10:56 53人阅读 评论(0) 收藏
  6. 解决Xcode6.4安装插件后插件不能使用的问题
  7. 手机无须ROOT不用修改hosts即可在本地测试安卓、苹果APP和H5应用
  8. JavaScript学习日志(四):BOM
  9. “百度杯”CTF比赛 九月场_SQLi
  10. client.go
  11. SQL反模式学习笔记3 单纯的树
  12. Docker容器集群管理之Swarm
  13. codeforces547a
  14. hdu5954 Do not pour out【积分】【二分】【待补.....】
  15. CentOS安装setup
  16. CF97C Winning Strategy
  17. Java Servelet
  18. Android 代码集装箱
  19. SVN错误记录
  20. 通过SSRS创建动态分组报表的方法!

热门文章

  1. time模块的time方法、perf_counter方法和process_time方法的区别
  2. Linux性能优化从入门到实战:14 文件系统篇:Linux 文件系统基础
  3. oralce 汇编02
  4. 10 | MySQL为什么有时候会选错索引? 学习记录
  5. Linux shell中自动完成登录
  6. pandas数据查询(数值、列表、区间、条件、函数)
  7. java判断回文数
  8. Android App渗透测试工具汇总
  9. LOJ 2840「JOISC 2018 Day 4」糖
  10. windows下zookeeper集群安装