Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中修饰生成器:在两者之间调用一些方法_Python_Generator_Decorator - Fatal编程技术网

在Python中修饰生成器:在两者之间调用一些方法

在Python中修饰生成器:在两者之间调用一些方法,python,generator,decorator,Python,Generator,Decorator,我从中找到了一些非常有用的信息,这些信息是关于在Python中使用yield修饰生成器函数的。例如: def mydec(func): def wrapper(*args, **kwargs): print(f'Getting values from "{func.__name__}"...') x = yield from func(*args, **kwargs) print(f'Got value {x}') retu

我从中找到了一些非常有用的信息,这些信息是关于在Python中使用
yield修饰生成器函数的。例如:

def mydec(func):
    def wrapper(*args, **kwargs):
        print(f'Getting values from "{func.__name__}"...')
        x = yield from func(*args, **kwargs)
        print(f'Got value {x}')
        return x
    return wrapper

@mydec
def mygen(n):
    for i in range(n):
        yield i
但是,这似乎只允许在生成器生命周期的开始和结束时添加装饰行为:

>>> foo = mygen(3)
>>> x = next(foo)
Getting values from "mygen"...
>>> x
0
>>> x = next(foo)
>>> x
1
>>> x = next(foo)
>>> x
2
>>> x = next(foo)
Got value None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> x
2
因此,每次产量都会调用
print
,但产量值保持不变


这可能吗?

的收益来自于协同程序。你不是在做协同工作。只需迭代生成器:

def mydec(func):
    def wrapper(*args, **kwargs):
        print(f'Getting values from "{func.__name__}"...')
        gen = func(*args, **kwargs)
        for value in gen:
            print(f'got value {value}')
            yield value
    return wrapper

对不起,我想我的问题不太清楚。我不希望字符串成为返回值,我只希望在每次生成器生成时运行一些行为,例如
print
语句。但是,decorator不应该修改
next()
返回的值。好的,我看到您编辑了这个问题。好吧,现在更容易了——这只是一个简单的旧for循环。
def mydec(func):
    def wrapper(*args, **kwargs):
        print(f'Getting values from "{func.__name__}"...')
        gen = func(*args, **kwargs)
        for value in gen:
            print(f'got value {value}')
            yield value
    return wrapper