python(4): 装饰器(Decorator)

文章目录

1 由来

装饰器也叫包装器(Wrapper),是Python对函数的一种包装。
因为python中“一切皆对象”,函数也是一个对象,可以赋值给变量:

def foo():
    print('This is foo() method.')

f = foo

print(f.__name__)
f()

执行结果为:

foo
This is foo() method.

如果需要增强foo()函数功能,又不想修改其定义,则可以通过装饰器来实现。

2 装饰器

本质上,decorator接受函数作为参数,就是一个返回函数的高阶函数。

def decor(fun):
    def wrapper(*args, **kwargs):
        print('wrapper function')
        return fun(*args, **kwargs)
    return wrapper

@decor
def haha(a , b):
    c = a + b
    print('haha', c)

def hehe(a, b):
    c = a + b
    print('hehe', c)

haha(2,3)	# 等价于 decor(hehe)(2, 3)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值