Skip to main content
 首页 » 编程设计

带有函数的python包装函数

2024年11月24日9kevingrace

我有下面这两个函数。我想先运行 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) 

请您参考如下方法:

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