首页 > 编程语言 > 详细

Python装饰器单例

时间:2018-10-18 20:02:16      阅读:154      评论:0      收藏:0      [点我收藏+]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dutsoft/article/details/52057981
#!/usr/bin/python
#coding: utf-8
"""
an elegant way to spawn singleton
"""

def singleton(cls, *args, **kw):
""" singleton decorator """
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton

@singleton
class TestClass(object):
a = 1
def __init__(self, x=0):
self.x = x


if __name__ == ‘__main__‘:
one = TestClass()
two = TestClass()

print one.a
print id(one)
print id(two)
print one is two
one.x = 1
print one.x
print two.x
---------------------
作者:dutsoft
来源:CSDN
原文:https://blog.csdn.net/dutsoft/article/details/52057981
版权声明:本文为博主原创文章,转载请附上博文链接!

Python装饰器单例

原文:https://www.cnblogs.com/ExMan/p/9812768.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!