可以写这样的东西:
class Test(object):
def _decorator(self, foo):
foo()
@self._decorator
def bar(self):
pass
失败:@self 中的 self 未知
我也尝试过:
@Test._decorator(self)
也失败了:测试未知
我想暂时更改一些实例变量 在装饰器中,然后运行装饰方法,之前 将它们改回来。
最佳答案
这样的东西可以满足您的需要吗?
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()
这避免了调用 self 来访问装饰器,并将其作为常规方法隐藏在类命名空间中。
>>> import stackoverflow
>>> test = stackoverflow.Test()
>>> test.bar()
start magic
normal call
end magic
>>>
<小时/>
编辑回答评论中的问题:
如何在另一个类中使用隐藏的装饰器
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
输出:
Normal:
start magic
normal call
end magic
Inherited:
start magic
override bar in
start magic
normal call
end magic
override bar out
end magic
关于类中的 Python 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55951157/