【发布时间】:2021-05-06 14:39:07
【问题描述】:
我刚刚编码的问题的 mwe:
from decorator import decorator
@decorator
def deco(func, deco_name=None, *args, **kwargs):
print(f"DECORATOR {deco_name} APPLIED")
return func(*args, **kwargs)
deco_name = None
class Greeter:
def __init__(self, _deco_name):
global deco_name
deco_name = _deco_name
@deco(deco_name=deco_name)
def hello(self, name):
print(f"Hello {name} :)")
print(deco_name)
g = Greeter("MYDECO")
g.hello("Yoshi")
控制台输出:
DECORATOR None APPLIED
Hello Yoshi :)
MYDECO
我的项目中有类似的设置,但我不明白为什么装饰器函数 deco() 不知道全局变量 deco_name 的更新值的值(它打印 DECORATOR None APPLIED 而不是 DECORATOR MYDECO APPLIED )。 装饰函数 hello() 确实知道最后一个打印语句生成的 MYDECO 所看到的更新值。 我需要一些方法来在运行时设置一个全局变量并将其传递给装饰器,如果有人可以 a) 向我解释为什么我的方法是错误的并且 b) 给我一个修复/替代解决方案,我会很高兴。
提前致谢。
【问题讨论】:
-
打印语句的顺序应该是胶水。装饰器的代码在类创建时被调用,在实例之前和
__init__()之前。
标签: python global-variables decorator