python - 是否可以在运行时替换 Python 函数/方法装饰器?

标签 python runtime language-features decorator

如果我有一个功能:


@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/

相关文章:

c# - 我应该使用 Guid 和 Guid.Empty 还是可以为 null 的 Guid?

python - 这段代码说明了什么 python 功能?

python 将两个不同的列表合并为一个

android 应用程序在运行时添加内容

c - sprintf() 程序未定义返回值

algorithm - lg * N在算法分析中的意义

python - 如何在 python 中打印 'user imported' 模块名称和版本

python - python中的Language_check继承错误

javascript - 如何将SQL Server中的数据绑定(bind)到Highcharts?