python高级进阶_6_无参数,有参数, 可变参数 装饰器的应用03

请看下 无参数的装饰器

如下:

def test(func):
    print("test")
    def test_in():
        print("testing")
        return "test  "+func()+"   test"
    return test_in

def test01(func):
    print("test01")
    def test_in():
        print("testing_01")
        return "test01  "+func()+"   test01"

    return test_in
@test
@test01
def f1():
    print("---f1----")
    return "hello_word"


print(f1())

请看有两个参数的

def test(func):
    print("test")
    def test_in():
        print("testing")
        return "test  "+func()+"   test"
    return test_in
@test
def f1(a,b):
    print("---f1----")
    return "hello_word"
print(f1(2,3))  # 传入两个参数 

抛错如下:

 File "D:/works/Unittest/test.py", line 14, in <module>
    print(f1(2,3))
TypeError: test_in() takes 0 positional arguments but 2 were given

理解下 为什么会抛错

  1. @ test 意思就是 f1=test(f1) , f1 指向是 test_in 函数体
  2. 在执行 f1(2,3) 的时候 要执行 test_in 函数体, 但是test_in 没有地方接受参数, 所以要报错
    下边我们添加上 继续执行看看结果如何:
def test(func):
    print("test")
    def test_in(a,b):
        print("testing")
        return "test  "+func()+"   test"
    return test_in


@test
def f1(a,b):
    print("---f1----")
    return "hello_word"

print(f1(2,3))


报错如下:

 File "D:/works/Unittest/test.py", line 14, in <module>
    print(f1(2,3))
  File "D:/works/Unittest/test.py", line 5, in test_in
    return "test  "+func()+"   test"
TypeError: f1() missing 2 required positional arguments: 'a' and 'b'

解释如下:

  1. 在执行test_in 函数体的时候, 发现有个 func(), 它的指向 就是 f1(a,b) , 它是需要两个参数的, 但是找不到,就会报错
    改下 再执行就不会报错了
def test(func):
    print("test")
    def test_in(a,b):
        print("testing")
        return "test  "+func(a,b)+"   test"
    return test_in


@test
def f1(a,b):
    print("---f1----")
    return "hello_word"

print(f1(2,3))

3. 可变参数

修改如下 就可以随便传递参数。

def test(func):
    print("test")
    def test_in(*args,**kargs):
        print("testing")
        return "test  "+str(func(*args,**kargs))+"   test"
    return test_in


@test
def f1(a,b):
    print("---f1----")
    return  a+b

@test
def f2(a,b,c,d):
    return(a+b+c+d)
print(f1(5,9))
print(f2(1,3,4,5))



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值