有可能这样做吗?
def my_func():
my_list = ['abc', 'def', 'ghi']
my_str = 'abc'如果我将A传递给装饰器,并将函数中的'abc‘替换为'xxx’,则传递B -> yyy
@装饰器(‘abc’)
def my_func():
my_list = ['xxx', 'def', 'ghi']
my_str = 'xxx'我不知道这是不是可能。
我该怎么做呢?
发布于 2019-10-23 12:29:07
可以用装饰器替换函数的代码对象,从而替换其中的常量,但这不太可能是您真正想要的解决方案。
这几乎在任何规模下都是不可维护的,因为你会有很大的部分看起来像这样:
# Note, this is python 3.x specific
CodeType(
argcount, # integer
kwonlyargcount, # integer
nlocals, # integer
stacksize, # integer
flags, # integer
codestring, # bytes
consts, # tuple
names, # tuple
varnames, # tuple
filename, # string
name, # string
firstlineno, # integer
lnotab, # bytes
freevars, # tuple
cellvars, # tuple
)其中您需要从原始代码对象复制,并根据您的意图对其进行修改。
对于这类问题,更好的解决方案是允许将字符串作为参数传递给函数。如果您需要函数稍后在没有字符串的情况下可调用,则可以使用partial (参见functools.partial)
https://stackoverflow.com/questions/58515362
复制相似问题