带函数的python wrap函数

2024-04-23 04:51:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下两个功能。我想先运行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)

Tags: 数据方法功能child编辑datareturndef
1条回答
网友
1楼 · 发布于 2024-04-23 04:51:11

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

相关问题 更多 >