python - 如何创建一个装饰器来装饰生成器函数?
问题描述
我需要创建一个装饰器函数来装饰生成器函数。生成器函数产生问题 # 以作为装饰添加。装饰器需要接受一个引用函数的参数。包装器需要返回一个格式化字符串,即提示“问题#:”,其中# 将是通过在生成器对象上调用 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
解决方案
如果您有一个简单的生成器,它会产生如下问题:
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']
推荐阅读
- excel - 后期绑定编译错误:在 Excel VBA 中未定义引用 Outlook 邮件项的用户定义类型
- php - CaBundle open_basedir 限制
- java - 我正在尝试在 exoplayer 中提取 youtube url。我想在日志中提取我的 sparsarray 值
- python - Installing mathplotlib gives "MemoryError"
- c# - 如何在 c# 代码中添加几个表?
- google-sheets - Only show a portion of a live Google sheet
- javascript - Java script pass function with arguments to another function
- java - 我正在创建 java api 来连接 kafka
- android - 离子构建失败
- c# - 如何获取不在同一类中的字符串的值?