Simple decorator using

Decorators are used to supplement existing functions. Without modifying the code of the original function, functions can be added to the parameters of the original function, before and after execution.

def checker(func):
    def inner(*args, **kwargs):
        print("执行前检查")
        print(args, kwargs)
        if args[0] <10:
            print('值小于10,不通过')
            raise ValueError
        return func(*args, **kwargs)
    return inner
@checker
def add_num(a, b=11):
    """"普通的相加函数,在装饰器中追加验证:a必须大于10"""
    print(a+b)
add_num(12,b=14)
add_num(1, b=14)

The output is as follows

执行前检查
(12,) {
    
    'b': 14}
26
执行前检查
(1,) {
    
    'b': 14}
值小于10,不通过
  File "/Users/tomjerry/PycharmProjects/pythonProject/main.py", line 22, in inner
    raise ValueError
ValueError

The args and kwargs in the decorator represent the two parameters in the decorated function respectively, arg represents the formal parameter without default value of the original function, and kwargs represents the formal parameter with default value in the function

Guess you like

Origin blog.csdn.net/qq_20728575/article/details/126344117
Recommended