擅长:python、mysql、java
<p>单粒子通过保持内部状态来实现这一点。这里的状态可能是类的一个实例。装饰师可以是任意的。在</p>
<p>看看这个:</p>
<p><a href="http://hairysun.com/downloads/DecoratorHandout.pdf" rel="nofollow">http://hairysun.com/downloads/DecoratorHandout.pdf</a></p>
<pre><code>class Decorator(object):
# in __init__ set up state
def __call__(self, function):
@functools.wraps(function)
def wrapper(*args, **kw): # 1.
print "before func"
result = function(*args, **kw) # 2.
print "after func"
return result
return wrapper # 3.
>>> decorator2 = Decorator()
>>> @decorator2
... def nothing(): pass
</code></pre>
<p>decorator本质上是一个函数</p>
<ol>
<li>定义函数</li>
<li>调用您传入的函数</li>
<li>返回稍后要调用的新“wrapped”函数</li>
</ol>
<p>周围的类(这里是decorator)可以这样做:</p>
^{pr2}$
<p>我没有运行代码,但我假设这是一般的工作方式。如果没有可用实例,请创建一个实例。如果有一个可用的,不要创建一个新的,而是返回一个旧的。在生产中使用此属性之前,可能需要检查可调用的其他属性。在</p>