<p>这样的东西能满足你的需要吗?</p>
<pre><code>class Test(object):
def _decorator(foo):
def magic( self ) :
print "start magic"
foo( self )
print "end magic"
return magic
@_decorator
def bar( self ) :
print "normal call"
test = Test()
test.bar()
</code></pre>
<p>这避免了调用self来访问decorator,并将其作为常规方法隐藏在类命名空间中。</p>
<pre><code>>>> import stackoverflow
>>> test = stackoverflow.Test()
>>> test.bar()
start magic
normal call
end magic
>>>
</code></pre>
<hr/>
<p>编辑以回答评论中的问题:</p>
<p>如何在另一个类中使用隐藏的decorator</p>
<pre><code>class Test(object):
def _decorator(foo):
def magic( self ) :
print "start magic"
foo( self )
print "end magic"
return magic
@_decorator
def bar( self ) :
print "normal call"
_decorator = staticmethod( _decorator )
class TestB( Test ):
@Test._decorator
def bar( self ):
print "override bar in"
super( TestB, self ).bar()
print "override bar out"
print "Normal:"
test = Test()
test.bar()
print
print "Inherited:"
b = TestB()
b.bar()
print
</code></pre>
<p>输出:</p>
<pre><code>Normal:
start magic
normal call
end magic
Inherited:
start magic
override bar in
start magic
normal call
end magic
override bar out
end magic
</code></pre>