如果我有一个功能:
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
是否可以在运行时替换装饰器?
最佳答案
正如 Miya 提到的,您可以在解释器到达该函数声明之前的任何时候用另一个函数替换装饰器。但是,一旦将装饰器应用于函数,我认为没有办法用不同的装饰器动态替换装饰器。比如:
@aDecorator
def myfunc1():
pass
# Oops! I didn't want that decorator after all!
myfunc1 = bDecorator(myfunc1)
不起作用,因为 myfunc1 不再是您最初定义的函数;它已经被包裹了。这里最好的方法是手动应用装饰器,oldskool 风格,即:
def myfunc1():
pass
myfunc2 = aDecorator(myfunc1)
myfunc3 = bDecorator(myfunc1)
编辑:或者,更清楚一点,
def _tempFunc():
pass
myfunc1 = aDecorator(_tempFunc)
myfunc1()
myfunc1 = bDecorator(_tempFunc)
myfunc1()
关于python - 是否可以在运行时替换 Python 函数/方法装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/642762/