Python 修改生成器值的装饰器

Python 修改生成器值的装饰器,python,python-3.x,Python,Python 3.x,我有一个类,这个类的每个方法都会产生一个字典。我想创建一个decorator,它将当前日期和时间添加到dictionary中,dictionary由一个方法生成。我已经实现了基于函数的解决方案,所以看起来是这样的: from pprint import pprint from datetime import datetime def _concat_datetime(func): def wrapper(): for document in func():

我有一个类,这个类的每个方法都会产生一个字典。我想创建一个decorator,它将当前日期和时间添加到dictionary中,dictionary由一个方法生成。我已经实现了基于函数的解决方案,所以看起来是这样的:

from pprint import pprint
from datetime import datetime


def _concat_datetime(func):
    def wrapper():
        for document in func():
            yield {
                **document,
                "current_date": datetime.now().strftime("%Y-%m-%d"),
                "current_time": datetime.now().strftime("%H:%M:%S"),
            }
    yield from wrapper()



@_concat_datetime 
def test():
    yield {
        "a": "a",
        "b": "b",
        "c": "c"
    }
for doc in test:
    pprint(doc)
输出:

{
‘a’:‘a’,
‘b’:‘b’,
‘c’:‘c’,
“当前日期”:“2019-11-19”,
“当前时间”:“15:35:31”
}

然而,使用基于类的解决方案,我得到了一个冲突,与
self
关键字有关。我发现,我需要将
self
传递到
wrapper()
。但我不知道从哪里得到它

基于类的解决方案:

class TestClass:

    def _concat_datetime(func):
        def wrapper(self):
            for document in func(self):
                yield {
                    **document,
                    "current_date": datetime.now().strftime("%Y-%m-%d"),
                    "current_time": datetime.now().strftime("%H:%M:%S"),
                }
        yield from wrapper()


    @_concat_datetime
    def test(self):
        yield {
            "a": "a",
            "b": "b",
            "c": "c"
        }


obj = TestClass()

for doc in obj.test:
    pprint(doc)

非常感谢您提前查看此帖子和所有建议。

只需返回生成器函数,而不是从生成器中让步

class TestClass:

    def _concat_datetime(func):
        def wrapper(self):
            for document in func(self):
                yield {
                    **document,
                    "current_date": datetime.now().strftime("%Y-%m-%d"),
                    "current_time": datetime.now().strftime("%H:%M:%S"),
                }
        return wrapper


    @_concat_datetime
    def test(self):
        yield {
            "a": "a",
            "b": "b",
            "c": "c"
        }

我不确定是否正确理解了所有内容,但我觉得您只需要返回修饰过的方法,而不是返回生成器。在相同的情况下,您可以使用一个测试函数来生成多个字典:

从pprint导入pprint
从日期时间导入日期时间
类TestClass:
定义时间(func):
def包装器(自身):
对于func(self)中的文档:
屈服{
**文件,
“当前日期”:datetime.now().strftime(“%Y-%m-%d”),
“当前时间”:datetime.now().strftime(“%H:%M:%S”),
}
返回包装器
@_连续日期时间
def测试(自我):
产量指令(枚举([“a”、“b”、“c”]))
产量指令(枚举([“d”、“e”、“f”]))
obj=TestClass()
对于obj.test()中的文档:
pprint(文件)
哪张照片

{0: 'a',
 1: 'b',
 2: 'c',
 'current_date': '2019-11-19',
 'current_time': '15:01:07'}
{0: 'd',
 1: 'e',
 2: 'f',
 'current_date': '2019-11-19',
 'current_time': '15:01:07'}