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