繁体   English   中英

python wrap 函数与函数

[英]python wrap function with function

我在下面有这两个功能。 我想先运行验证然后是孩子,但我想用验证装饰孩子,这样我就可以告诉它先在给定的输入上运行验证,然后将输出传递给孩子以在其上运行。

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)

请注意, @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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM