相关疑难解决方法(0)

Python装饰器有哪些常见用途?

虽然我喜欢把自己想象成一个相当称职的Python编码器,但我从来没有能够理解的语言的一个方面就是装饰器.

我知道它们是什么(表面上),我已经阅读了有关Stack Overflow的教程,示例和问题,我理解语法,可以编写自己的,偶尔使用@classmethod和@staticmethod,但我从来没有想过使用装饰器解决我自己的Python代码中的问题.我从来没有遇到过这样的问题,"嗯......这看起来像装饰工作!"

所以,我想知道你们是否可以提供一些你在自己的程序中使用装饰器的例子,希望我会有一个"A-ha!" 一刻,得到他们.

python decorator

328
推荐指数
11
解决办法
7万
查看次数

79
推荐指数
2
解决办法
2万
查看次数

为什么这个单例实现"不是线程安全的"?

1. @Singleton装饰

我找到了一种优雅的方法来装饰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)

python singleton multithreading python-3.x python-3.6

5
推荐指数
2
解决办法
4507
查看次数