【问题标题】:python wrap function with functionpython wrap函数与函数
【发布时间】:2019-12-06 04:10:57
【问题描述】:

我在下面有这两个功能。我想先运行 validate 然后运行 ​​child 但我想用 validate 装饰 child 以便我可以告诉它首先对给定的输入运行 validate 然后将输出传递给 child 以在其上运行。

def validate(x, y):
    print(x, y)
    x = x+2
    y = y +1
    return x, y


def child(x, y):
    print(x)
    print(y)
    return x, y

我该怎么做?

显然,这不起作用:

def validate(x):
    print(x)
    x = x+2
    return x

@validate
def child(x):
    print(x)
    return x

我想以装饰者的方式实现这样的目标:

child(validate(2))

编辑:

我有一些方法'data_parsing'接受输入并对输入的数据进行一些登录。数据可能出现故障,所以我创建了一个类,其中包含首先验证输入数据的方法。如果数据格式错误,我会实例化该类并首先运行验证引发异常。如果成功,我将进入下一个函数调用data_parsing(),它获取数据并处理它。所以逻辑是:

def execute(data):
    validator_object(data).run()
    data_parsing(data)

编辑:

def validator(fnc):
    def inner(*aaa):
        a,b = aaa
        a += 4
        return fnc(a,b)
    return inner

@validator
def child(*aaa):
    a,b = aaa
    print(a)
    return a

a = 1
b = 2
child(a, b)

【问题讨论】:

  • 很好看。谢谢你。我刚刚编辑了我的问题。
  • 在本例中是的,但在实际示例中,我想先验证一些数据,运行一些验证方法,如果成功则将数据返回给子函数以进行进一步处理。
  • 参见示例。您可以在内部闭包中添加验证。

标签: python decorator wrapper


【解决方案1】:

请注意@decorator 形式应用于函数声明阶段,它会立即包装目标函数。

您可以为您的案例使用以下实现:

def validate(f):
    @functools.wraps(f)
    def decor(*args, **kwargs):
        x, y = args
        if x <= 0 or y <= 0:
            raise ValueError('values must be greater than 0')
        print('--- validated value', x)
        print('--- validated value y', y)
        x = x+2
        y = y+1
        res = f(x, y, **kwargs)
        return res
    return decor

@validate
def child(x, y):
    print('child got value x:', x)
    print('child got value y:', y)
    return x, y


child(3, 6)
child(0, 0)

样本输出:

--- validated value x 3
--- validated value y 6
child got value x: 5
child got value y: 7
Traceback (most recent call last):
  File "/data/projects/test/functions.py", line 212, in <module>
    child(0, 0)
  File "/data/projects/test/functions.py", line 195, in decor
    raise ValueError('values must be greater than 0')
ValueError: values must be greater than 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多