当前位置:脚本大全 > > 正文

python使用教程操作(详解python中@的用法)

时间:2021-10-29 14:19:22类别:脚本大全

python使用教程操作

详解python中@的用法

python中@的用法

@是一个装饰器,针对函数,起调用传参的作用。
有修饰和被修饰的区别,‘@function'作为一个装饰器,用来修饰紧跟着的函数(可以是另一个装饰器,也可以是函数定义)。

代码1

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • def funA(desA):
  •  print("It's funA")
  •  
  • def funB(desB):
  •  print("It's funB")
  •  
  • @funA
  • def funC():
  •  print("It's funC")
  • 结果1

    It's funA

    分析1

    @funA 修饰函数定义def funC(),将funC()赋值给funA()的形参。
    执行的时候由上而下,先定义funA、funB,然后运行funA(funC())。
    此时desA=funC(),然后funA()输出‘It's funA'。

    代码2

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • def funA(desA):
  •  print("It's funA")
  •  
  • def funB(desB):
  •  print("It's funB")
  •  
  • @funB
  • @funA
  • def funC():
  •  print("It's funC")
  • 结果2

    It's funA
    It's funB

    分析2

    @funB 修饰装饰器@funA,@funA 修饰函数定义def funC(),将funC()赋值给funA()的形参,再将funA(funC())赋值给funB()。
    执行的时候由上而下,先定义funA、funB,然后运行funB(funA(funC()))。
    此时desA=funC(),然后funA()输出‘It's funA';desB=funA(funC()),然后funB()输出‘It's funB'。

    代码3

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • def funA(desA):
  •  print("It's funA")
  •  
  •  print('---')
  •  print(desA)
  •  desA()
  •  print('---')
  •  
  • def funB(desB):
  •  print("It's funB")
  •  
  • @funB
  • @funA
  • def funC():
  •  print("It's funC")
  • 结果3

    It's funA
    < function funC at 0x000001A5FF763C80 >
    It's funC
    It's funB

    分析3

    同上,为了更直观地看参数传递,打印desA,其传的是funC()的地址,即desA现在为函数desA()。
    执行desA()即执行funC(),desA=desA()=funC()。

    代码4

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • def funA(desA):
  •  print("It's funA")
  •  
  • def funB(desB):
  •  print("It's funB")
  •  print('---')
  •  print(desB)
  •  
  • @funB
  • @funA
  • def funC():
  •  print("It's funC")
  • 结果4

    It's funA
    It's funB
    None

    分析4

    上面将funC()作为参数传给funA,那么funA(funC())怎么传给funB()呢?打印desB,发现并没有参数传递。
    是否可以理解为当‘装饰器' 修饰 ‘装饰器'时,仅是调用函数。

    以上所述是小编给大家介绍的python中@的用法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对开心学习网网站的支持!

    原文链接:https://blog.csdn.net/occamo/article/details/80842311

    标签:
    上一篇下一篇

    猜您喜欢

    热门推荐