版权声明:本文为博主原创文章,未经博主允许不得转载。 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
版权声明:本文为博主原创文章,转载请附上博文链接!