擅长:python、mysql、java
<p>不,这是不可能的,因为绑定方法和函数之间没有内在的区别。方法就是一个简单的函数,它将调用实例作为第一个参数(使用Python<a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow noreferrer">descriptors</a>)。在</p>
<p>像这样的电话:</p>
<pre><code>Test.test_call
</code></pre>
<p>它返回一个未绑定的方法,转换为</p>
^{pr2}$
<p>这是一个未绑定的方法,尽管</p>
<pre><code>Test.__dict__[ 'test_call' ]
</code></pre>
<p>是一个函数。这是因为函数是其<code>__get__</code>方法返回方法的描述符;当Python在查找链中看到其中一个方法时,它将调用<code>__get__</code>方法,而不是继续向上延伸。在</p>
<p>实际上,函数的“绑定方法”是在运行时确定的,而不是在定义时确定的!在</p>
<p>decorator只看到定义的函数,而不在<code>__dict__</code>中查找它,因此无法判断它是否在查看绑定方法。在</p>
<hr/>
<p>使用修改<code>__getattribute__</code>的类修饰符可以实现这一点,但这是一种特别讨厌的黑客攻击。为什么一定要有这个功能?当然,由于您必须自己将decorator放在函数上,所以您可以向它传递一个参数,说明所述函数是否在类中定义?在</p>
<pre><code>class Test:
@decorate( method = True )
def test_call:
...
@decorate( method = False )
def test_call:
...
</code></pre>