虽然我喜欢把自己想象成一个相当称职的Python编码器,但我从来没有能够理解的语言的一个方面就是装饰器.
我知道它们是什么(表面上),我已经阅读了有关Stack Overflow的教程,示例和问题,我理解语法,可以编写自己的,偶尔使用@classmethod和@staticmethod,但我从来没有想过使用装饰器解决我自己的Python代码中的问题.我从来没有遇到过这样的问题,"嗯......这看起来像装饰工作!"
所以,我想知道你们是否可以提供一些你在自己的程序中使用装饰器的例子,希望我会有一个"A-ha!" 一刻,得到他们.
我找到了一种优雅的方法来装饰Python类来实现它singleton.该类只能生成一个对象.每次Instance()调用都返回相同的对象:
class Singleton:
"""
A non-thread-safe helper class to ease implementing singletons.
This should be used as a decorator -- not a metaclass -- to the
class that should be a singleton.
The decorated class can define one `__init__` function that
takes only the `self` argument. Also, the decorated class cannot be
inherited from. Other than that, there are no restrictions that apply
to the decorated class.
To get the singleton instance, use the …Run Code Online (Sandbox Code Playgroud)