如何在Python中使用装饰器验证参数

4

在调用add函数之前,我需要验证两个给定的输入:如果任何一个输入不是整数,我应该得到无效输入错误消息,如果两个都是整数,则应该得到它们的总和。

import re

def my_dec(arg1,arg2):
     x = re.compile(r"[^0-9]")
     if x.search(arg1) and x.search(arg2):
        return add(a,b)
     else:
         print("invalid input")

@my_dec(arg1,arg2)
def add(a,b):
   return a + b

print(add(2,3))

我在循环中遇到“函数未定义”的错误,但我不知道该如何解决它。

你的if语句中,在(arg2)后面缺少了一个“:”。 - akash
3个回答

1
经过大量的研究和工作,我找到了使用装饰器验证值并找到两个值的加法的解决方案。
import random

def decorator(func):
    def func_wrapper(x,y):
        if type(x) is int and type(y) is int:
            result = func(x,y)
            print(f"{x} + {y} = {result}")
            return result
        elif type(x) is not int or type(y) is not int:
            print("invalid input")
    return func_wrapper

def add(a, b):
    return a+b

在装饰器之前调用add函数:
print(add(4, 5))
    
add = decorator(add)

#check for different values and inputs
list_1 = [1, 2, 32, 4, 4, 65, 3, 2, 'A', 'D', None, False, True,
          0, 1, -2, 2, -33, 0.223, 212, 'string']
for i in range(1, 100):
    x = random.choice(list_1)
    y = random.choice(list_1)
    add(x, y)

1

1
装饰器接受一个函数,添加功能并返回它。请参考下面的代码来解决您的问题:
import re

def my_dec(func_name):

    def sub_dec(a, b):
        if re.match(r'\d',str(a)) and re.match(r'\d',str(b)):
            return func_name(a,b)
        else:
            print("invalid input")

    return sub_dec


@my_dec
def add(a,b):
    return a + b

print(add(2,3))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接