新网创想网站建设,新征程启航

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

python高级进阶之无参数,有参数,可变参数的装饰器的应用-创新互联

请看下 无参数的装饰器

创新互联主要从事成都网站设计、做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务扶沟,10余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575

如下:

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))

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文名称:python高级进阶之无参数,有参数,可变参数的装饰器的应用-创新互联
标题来源:http://www.wjwzjz.com/article/poesd.html
在线咨询
服务热线
服务热线:028-86922220
TOP