python装饰器

1、没有参数的装饰器

def test(func):
    def in_test():
        print("*"*100)
        func()
        print("*"*100)
    return in_test

@test
def demo():  #参数
    print("in func demo")

demo()

2、被装饰的函数带参数

(1)参数在装饰器内部定义:

def test(func):
    a = 100
    def in_test():
        print("*"*100)
        func(a)
        print("*"*100)
    return in_test

@test
def demo(cc):  #参数
    print("in func demo cc = ", cc)

demo()

(2)参数从外部传入:

def test(func):
    def in_test(a):
        print("*"*100)
        func(a)
        print("*"*100)
    return in_test

a = 100
@test
def demo(cc):  #参数
    print("in func demo cc = ", cc)

demo(a)

3、装饰器带参数

(1)装饰器和传入的参数函数都带参数:

def out(a): #外面这层函数就是为了把参数传入
    def test(func):
        def in_test(b):
            print("*"*100)
            func(a+b)
            print("*"*100)
        return in_test
    return test

a = 100
b = 15
@out(a)
def demo(cc):  #参数
    print("in func demo cc = ", cc)

demo(b)

(2)只装饰器带参数:

def out(a): #外面这层函数就是为了把参数传入
    def test(func):
        def in_test():
            print("*"*100)
            func(a)
            print("*"*100)
        return in_test
    return test

a = 100
@out(a)
def demo(cc):  #参数
    print("in func demo cc = ", cc)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值