[英]Decorator to modify a generator value
我有一個 class ,這個 class 的每個方法都會產生一個字典。 我想創建一個裝飾器,它將當前日期和時間添加到字典中,該字典由方法產生。 我已經實現了基於函數的解決方案,所以它看起來像這樣:
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)
Output:
{ 'a': 'a', 'b': 'b', 'c': 'c', 'current_date': '2019-11-19', 'current_time': '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)
非常感謝您提前查看這篇文章和所有建議。
只需返回生成器 function,而不是從生成器中屈服。
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"
}
我不確定是否正確理解所有內容,但我覺得您只需要返回裝飾方法而不是返回生成器。 在同樣的情況下,您可以使用產生幾個字典的測試 function:
from pprint import pprint
from datetime import datetime
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 dict(enumerate(["a", "b", "c"]))
yield dict(enumerate(["d", "e", "f"]))
obj = TestClass()
for doc in obj.test():
pprint(doc)
哪個打印
{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'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.