我在python中为单例使用了一个decorator,实现如下所示。你知道吗
我希望装饰类的pydoc与非装饰类的pydoc完全相同,但我不知道如何:
如果没有getSingletonInstance.__doc__ = cls.__doc__
行,修饰类的pydoc将给出singleton
函数的pydoc。
对于getSingletonInstance.__doc__ = cls.__doc__
行,修饰类的pydoc只给出“顶级”docstring。
我怎么继续?你知道吗
谢谢。你知道吗
def singleton(cls):
"""A singleton decorator
Warnings
--------
Singleton gdecorated calsses cannot be inhehited
Example
-------
>>> from decorators import singleton
>>> @singleton
... class SingletonDemo():
... pass
>>> d1 = SingletonDemo()
>>> d1.a = 0xCAFE
>>> d2 = SingletonDemo()
>>> id(d1) == id(d2)
True
>>> d1 == d2
True
>>> d2.a == 0xCAFE
True
References
----------
See case 2 of https://www.python.org/dev/peps/pep-0318/#examples
"""
_instances = {}
def getSingletonInstance():
if cls not in _instances:
_instances[cls] = cls()
return _instances[cls]
getSingletonInstance.__doc__ = cls.__doc__
return getSingletonInstance
尝试使用
functools.wraps
:用例子总结所有的讨论。 非常感谢大家。你知道吗
此解决方案:
限制:
解决方案: 定义单例(cls):
相关问题 更多 >
编程相关推荐