重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

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

请看下 无参数的装饰器

成都创新互联公司坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站制作、网站建设、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的新野网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

如下:

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

print(f1(2,3))

TypeError: test_in() takes 0 positional arguments but 2 were given

理解下 为什么会抛错

@ test 意思就是 f1=test(f1) , f1 指向是 test_in 函数体

在执行 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

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'

解释如下:无锡妇科医院排名 http://www.csfk0731.com/

在执行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))


网站标题:python高级进阶之无参数,有参数,可变参数的装饰器的应用
URL地址:http://cqcxhl.cn/article/igjhpd.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP