详解python中@的用法
作者:occamo 时间:2022-05-15 04:52:32
python中@的用法
@是一个装饰器,针对函数,起调用传参的作用。
有修饰和被修饰的区别,‘@function'作为一个装饰器,用来修饰紧跟着的函数(可以是另一个装饰器,也可以是函数定义)。
代码1
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
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
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
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
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
mysql性能的检查和调优方法
Python安装第三方库及常见问题处理方法汇总
tf.concat中axis的含义与使用详解
详解微信小程序文件下载--视频和图片
浅谈opencv自动光学检测、目标分割和检测(连通区域和findContours)
![](https://img.aspxhome.com/file/2023/0/75890_0s.jpg)
ImageMagicK convert crop参数说明
CGArt®2008 贺岁刊电子杂志玉鼠闹春
![](https://img.aspxhome.com/file/UploadPic/20082/15/200821511345421s.jpg)
python配置虚拟环境步骤
![](https://img.aspxhome.com/file/2023/1/92011_0s.png)
安装docker-compose的两种最简方法
彻底弄清楚haslayout概念
windows下Python安装、使用教程和Notepad++的使用教程
![](https://img.aspxhome.com/file/2023/6/86366_0s.png)
[新手必看]15个asp编程常见问题解答
![](https://img.aspxhome.com/file/UploadPic/up/2007082213545326.jpg)
PHP convert_cyr_string()函数讲解
![](https://img.aspxhome.com/file/2023/4/55394_0s.png)
tensorflow实现图像的裁剪和填充方法
![](https://img.aspxhome.com/file/2023/0/59820_0s.jpg)
python使用wxpython开发简单记事本的方法
![](https://img.aspxhome.com/file/2023/2/86392_0s.png)
初步探究Python程序的执行原理
![](https://img.aspxhome.com/file/2023/7/82747_0s.png)
Python基础篇之初识Python必看攻略
![](https://img.aspxhome.com/file/2023/4/99604_0s.png)
SQL处理多级分类,查询结果呈树形结构
学习ASP.NET八天入门:第二天
![](https://img.aspxhome.com/file/UploadPic/20078/7/200787132851702s.gif)
Python实现笑脸检测+人脸口罩检测功能
![](https://img.aspxhome.com/file/2023/4/87474_0s.png)