温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-05 20:48:31 来源:网络 阅读:319 作者:nineteens 栏目:编程语言

  请看下 无参数的装饰器

  如下:

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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI