python decorate 的秘密

什么是decorate?

python decorate 就是python 的一种高阶函数用法。

例子详解, 管中窥豹。

def decorate_func(func):
    print("call decorate_func() here")
    def wrapper(*args, **kwargs):
        print(f"decorate_func- call wrapper and arguments are {args} + {kwargs}")
        func(*args, **kwargs)
    return wrapper


def timer_log(number):
    print(f"call time_log({number}) function")
    def decorate_func2(func):
        print("call decorate_func2 here")
        def wrapper(*args, **kwargs):
            print(f"decorate_func2 - call wrapper and arguments are {args} + {kwargs}")
            func(*args, **kwargs)

        return wrapper
    return decorate_func2


# the usage "@decorate_func()" is invalid. Error - TypeError: decorate_func() missing 1 required positional argument: 'func'
@decorate_func
def myfirstname(name):
    print(f"I am {name}")

@timer_log(10)
def mylastname(name):
    print(f"my last name is {name}")


myfirstname("Wu")
mylastname("Tom")
call decorate_func() here # 当python 解析到line 23, python 执行装饰器@decorate_func
call time_log(10) function # 当python 解析到line 27, python 先执行装饰器@timer_log(10),得到的返回值还是一个高阶函数decorate_func2
call decorate_func2 here # 再执行 decorate_func2
decorate_func- call wrapper and arguments are ('Wu',) + {} # 当代码执行到line31, myfirstname.__name__已经变成wrapper,所以执行 `myfirstname("Wu")` 就等于执行 wrapper 函数。
I am Wu
decorate_func2 - call wrapper and arguments are ('Tom',) + {}
my last name is Tom

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值