python装饰器

python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能。 

def dec1(func):
    print("1111")
    def one():
        print("2222")
        func()
        print("3333")
    return one

@dec1
def test():
    print("test test")

test()



返回结果:
1111
2222
test test
3333

带参数的装饰器

def dec1(func):
    print("aaaa")
    def one(a,b):
        print("----%d" % a)
        func(a,b)
        print("----%d" % b)
    return one

@dec1
def test(a,b):
    print("test test")

test(10,20)

执行结果:
aaaa
----10
test test
----20

不定参数的装饰器

def dec1(func):
    print("aaaa")
    def one(*args, **kwargs):
        print("bbbb")
        func(*args, **kwargs)
        print("cccc")
    return one

@dec1
def test(a,b):
    print("test test")

@dec1
def test1(c,d,e):
    print("test1 test1")

test(10,20)
test1(30,40,50)

返回结果:
aaaa
aaaa
bbbb
test test
cccc
bbbb
test1 test1
cccc

多个装饰器执行的顺序就是从最后一个装饰器开始,执行到第一个装饰器,再执行函数本身

def dec1(func):
    print("1111")
    def one():
        print("2222")
        func()
        print("3333")
    return one

def dec2(func):
    print("aaaa")
    def two():
        print("bbbb")
        func()
        print("cccc")
    return two

@dec1
@dec2
def test():
    print("test test")

test()

返回结果:
aaaa
1111
2222
bbbb
test test
cccc
3333

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值