如果 python 中的变量设置为 true,则修饰文件中的所有函数
Decorating all functions in a file if variable is set to true in python
我有密码
chop_flag = True
def decorator(func):
def chop_num(num):
num = str(num)
num = num[:15]
return float(num)
return chop_num
def decorator2():
return decorator if chop_flag else break
然后在程序中的每个函数之前添加 @decorator2
。这会产生类型错误(“decorator2() 接受 0 个位置参数,但给出了 1 个”)而且我也很确定这不是做我想做的事情的好方法。
总结一下:我正在尝试获取程序中每个函数的输出,并通过 chop_num()
函数 运行 如果 chop_flag = True
;如果 chop_flag = False
,我希望它忽略装饰器。我想我会通过为每个函数应用一个装饰器来做到这一点。任何帮助将不胜感激。
更新代码:
chop_flag = True
def decorator(func):
if chop_flag == True:
def chop_num(num, *args, **kwargs):
num = func(*args, **kwargs)
num = str(num)
num = num[:15]
return float(num)
return chop_num
else:
return
它现在 运行 正确,但是当我将我的文件导入解释器(例如)并调用 add 函数时,它说“add() 缺少 1 个必需的位置参数”,即使我有输入两个参数。
我认为你的最终装饰器应该看起来更像这样
def chop_num(num):
num = str(num)
num = num[:15]
return float(num)
chop_flag = True
def decorator(func):
def wrapper(*args, **kwargs):
val = func(*args, **kwargs)
if chop_flag:
return chop_num(val)
else:
return val
return wrapper
@decorator
def nineteen_digits():
return 1_000_000_000_000_000_000
print(nineteen_digits())
# 100000000000000.0
chop_flag = False
print(nineteen_digits())
# 1000000000000000000
我有密码
chop_flag = True
def decorator(func):
def chop_num(num):
num = str(num)
num = num[:15]
return float(num)
return chop_num
def decorator2():
return decorator if chop_flag else break
然后在程序中的每个函数之前添加 @decorator2
。这会产生类型错误(“decorator2() 接受 0 个位置参数,但给出了 1 个”)而且我也很确定这不是做我想做的事情的好方法。
总结一下:我正在尝试获取程序中每个函数的输出,并通过 chop_num()
函数 运行 如果 chop_flag = True
;如果 chop_flag = False
,我希望它忽略装饰器。我想我会通过为每个函数应用一个装饰器来做到这一点。任何帮助将不胜感激。
更新代码:
chop_flag = True
def decorator(func):
if chop_flag == True:
def chop_num(num, *args, **kwargs):
num = func(*args, **kwargs)
num = str(num)
num = num[:15]
return float(num)
return chop_num
else:
return
它现在 运行 正确,但是当我将我的文件导入解释器(例如)并调用 add 函数时,它说“add() 缺少 1 个必需的位置参数”,即使我有输入两个参数。
我认为你的最终装饰器应该看起来更像这样
def chop_num(num):
num = str(num)
num = num[:15]
return float(num)
chop_flag = True
def decorator(func):
def wrapper(*args, **kwargs):
val = func(*args, **kwargs)
if chop_flag:
return chop_num(val)
else:
return val
return wrapper
@decorator
def nineteen_digits():
return 1_000_000_000_000_000_000
print(nineteen_digits())
# 100000000000000.0
chop_flag = False
print(nineteen_digits())
# 1000000000000000000