2

我正在尝试使用装饰器对函数进行参数化。经过大量的打击和试验后,我终于能够按预期运行。但是我仍然不满意,好像它正在工作,这似乎不是正确的方法。

请帮助我改进此代码。

这是我的代码:

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() 
4

1 回答 1

1

也可以为WarmWelcome装饰器提供数据集权限:

def WarmWelcome(*data_sets):
    def _decorator(func):
        def _func():
            for ds in data_sets:
                func(*ds)
        return _func
    return _decorator

@WarmWelcome(
    ("abc", ),
    ("xyz", ),
    ("def", ),
)
def hello(name):
    return "hello " +name

原文:Python unittest 的类似 PHPUnit 的 dataProvider 实现

于 2013-11-21T15:15:31.337 回答