首页 > 解决方案 > 如何创建一个装饰器来装饰生成器函数?

问题描述

我需要创建一个装饰器函数来装饰生成器函数。生成器函数产生问题 # 以作为装饰添加。装饰器需要接受一个引用函数的参数。包装器需要返回一个格式化字符串,即提示“问题#:”,其中# 将是通过在生成器对象上调用 next 产生的数字。

我知道我的代码不正确,但我不知道如何修复它或从这里去哪里。任何帮助,将不胜感激

这是我目前拥有的:

def decorator(func):

    """decorator that constructs and saves a generator object"""

    gen_object = func()

    @wraps(func)
    def wrapper(*args, **kwargs):
        """wrapper"""
        question = func(*args, **kwargs)
        input(f'Question {question} <movie character>: ')
        return wrapper

标签: pythongeneratordecoratorwrapperpython-decorators

解决方案


如果您有一个简单的生成器,它会产生如下问题:

def someF():
    yield from [
        'Name a color',
        'Name an animal', 
        'Name a country'

]

然后你可以用一个装饰器包装它,这样它就可以遍历生成器并添加你想要的细节。如果您产生结果,input()您可以像任何其他生成器一样捕获输入:

from functools import wraps

def gen(f):
    @wraps(f)
    def inner(*args, **kwargs):
        g = f(*args, **kwargs)
        for num, question in enumerate(g):
            yield input(f'question #{num}: {question}: ')
    return inner
    
@gen
def someF():
    yield from [
        'Name a color', 
        'Name an animal', 
        'Name a country'
    ]

g = someF()
list(g)

使用它看起来像:

> question #0: Name a color: Blue
> question #1: Name an animal: Dog
> question #2: Name a country: Bolivia
['Blue', 'Dog', 'Bolivia']

推荐阅读