我应该编写一个装饰器,将给定格式的日期添加到函数返回的dict的参数中。这是我的密码:
import datetime # do not change this import, use datetime.datetime.now() to get date
def add_date(format):
def decorator(f):
def inner(*args):
dic=dict(f(*args))
dic['date']=datetime.datetime.now().strftime(format)
return dic
return inner
return decorator
@add_date('%B %Y')
def get_data(a=5):
return {1: a, 'name': 'Jan'}
assert get_data(2) == {
1: 2, 'name': 'Jan', 'date': 'April 2020'
}
但在运行强制性测试后,由于警报原因,我没有通过这些测试:
Traceback (most recent call last):
File "/home/runner/unit_tests.py", line 64, in test_add_date
self.assertEqual(get_data(a=5), {
TypeError: inner() got an unexpected keyword argument 'a'
我也不知道如何修复它。有什么建议吗
您正在将
5
作为关键字参数(a=5
)传递,但是inner
函数只接受位置参数(*args
)。让它像这样接受关键字参数(**kwargs
)将解决您的问题Check Python documentation for more information on positional and keyword arguments.
相关问题 更多 >
编程相关推荐