I've decorated a method in Python. And when I import the module that contains the method, the decorator autoruns.
I realize that this is how decorators were made however Is there a way to have decorators NOT do this?
I've decorated a method in Python. And when I import the module that contains the method, the decorator autoruns.
I realize that this is how decorators were made however Is there a way to have decorators NOT do this?
听起来您想要做的是选择在运行时应用什么装饰器。像这样的东西可能会起作用:
to_decorate = []
def decorate_later(func):
to_decorate.append(func)
return func
@decorate_later
def do_stuff(*args, **kw):
print('I am doing stuff')
@decorate_later
def do_more_stuff(*args, **kw):
print('Even more stuff')
def apply_decorator(decorator):
for func in to_decorate:
globals()[func.func_name] = decorator(func)
然后您可以导入模块,所有功能都将正常定义。 decorate_later
返回未修改的原始函数。您可以调用apply_decorator()
以将指定的装饰器应用于模块中注册的所有函数@decorate_later
利用
if __name__ == "__main__":
#code
在文件中,其中代码都在方法或类之外(在导入时运行)。