Python:Decorator可以从foo1()访问参数并将其提供给foo2()吗?

2024-04-20 09:48:39 发布

您现在位置:Python中文网/ 问答频道 /正文

更准确地说

@string_supply #This should supply **string** from foo1 into foo2
def foo2(x):
    #Cannot use global string. string changes
    return list(itertools.compress(string, x)) # **string** needed here

def foo1(startrange, string):
    temp = None
    temp_list = map(temp, start_range_compute_list(startrange))
    ls_of = map(foo2, temp_list)
    yield ls_of

@string\u supply decorator可以这样写吗?我对装修工没有经验。你知道吗


Tags: offrommapstringdefthistempls
1条回答
网友
1楼 · 发布于 2024-04-20 09:48:39

不,它不能。装饰程序不能访问装饰函数的内部。也许这是可以通过一些肮脏的黑客,但我认为最好避免这样的解决方案。你知道吗

从您描述的体系结构来看,似乎您需要一个带有实例变量的类。比如:

class Simple(object):
    def __init__(self):
        self._string = ""

    def foo2(self, x):
        #Cannot use global string. string changes
        return list(itertools.compress(self._string, x)) # **string** needed here

    def foo1(self, startrange, string):
        self._string = string
        temp = None
        temp_list = map(temp, start_range_compute_list(startrange))
        ls_of = map(foo2, temp_list)
        yield ls_of

相关问题 更多 >