擅长:python、mysql、java
<p>我无法想象满足这种要求的方法,因为<code>decor</code>函数只接收一个对包含类一无所知的函数对象。在</p>
<p>我能想到的唯一解决方法是使用参数化decorator并将被修饰的类传递给它</p>
<pre><code>def decor(cls):
def wrapper(method):
def wrapped(self, *args, **kwargs):
return self.method(*args, **kwargs)
print method # only a function object here
return wrapped
print cls # here we get the class and can manipulate it
return wrapper
class A
@decor(A)
def method(self):
pass
</code></pre>
<p>或者,可以装饰类本身:</p>
^{pr2}$
<p>给出:</p>
<pre class="lang-none prettyprint-override"><code>Decorating __main__.B
</code></pre>