#!/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
Python装饰器单例
最新推荐文章于 2024-05-16 08:35:41 发布