我正在尝试使用装饰器对函数进行参数化。经过大量的打击和试验后,我终于能够按预期运行。但是我仍然不满意,好像它正在工作,这似乎不是正确的方法。
请帮助我改进此代码。
这是我的代码:
def WarmWelcome(fn):
def wrapped(DataProvider):
for name in DataProvider():
print fn(name) + ":)"
return wrapped
def DataProvider():
names=["abc","xyz","def"]
for name in names:
yield name
@WarmWelcome
def hello(name):
return "hello " +name
hello(DataProvider)
这是更新的代码:
def WarmWelcome(DataProvider):
def real_decorator(fn):
def wrapped():
for name in DataProvider():
print fn(name) + ":)"
return wrapped
return real_decorator
def DataProvider():
names=["abc","xyz","def"]
for name in names:
yield name
@WarmWelcome(DataProvider)
def hello(name):
return "hello " +name
hello()