python函数常见关键字分享
作者:荼靡, 时间:2022-06-17 04:31:55
1.global关键字
默认情况下,在局部作用域对全局变量只能进行:读取,修改内部元素(可变类型),无法对全局变量进行重新赋值
读取:
CITY=['北京','上海']
def func():
print(CITY) # ['北京','上海']
func()
修改内部元素(可变类型)
CITY=['北京','上海']
def func():
CITY.append('安徽')
print(CITY) # ['北京','上海','安徽']
func()
print(CITY) # ['北京','上海','安徽']
无法对全局变量重新赋值
CITY=['北京','上海']
def func():
CITY=['安徽']
print(CITY) #['安徽']
func()
print(CITY) # ['北京','上海']
如果想在局部作用域对全局变量重新赋值,基于global关键字实现
CITY=['北京','上海']
def func():
global CITY=['安徽']
print(CITY) #['安徽']
func()
print(CITY) #['安徽']
2.nolocal关键字
将上一级作用域的变量重新赋值
name = 'root'
def outer():
# name=123
name = '你好'
def func():
# 将又上一级变量name重新赋值为123
nonlocal name
# name=123
name = "wxy"
def inner():
#将上一级变量name重新赋值为123
nonlocal name
name = 123
inner()
print(name)
func()
print(name)
outer()
print(name)
# 123
# 123
# root
3.yield from
python3.3引入yield from
在yield函数中调用其它的yield函数
def func():
yield 2
yield 2
def func1():
yield 1
yield 1
yield from func()
yield 1
from i in func1():
print(1)
来源:https://blog.csdn.net/m0_46926492/article/details/124382646
标签:python,函数,常见,关键字
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
通过T-SQL语句实现数据库备份与还原的代码
2011-12-01 08:02:15
Python中scatter散点图及颜色整理大全
2022-10-06 02:17:51
![](https://img.aspxhome.com/file/2023/2/83832_0s.png)
python3利用Socket实现通信的方法示例
2022-04-10 03:09:04
![](https://img.aspxhome.com/file/2023/7/107887_0s.png)
python中multiprosessing模块的Pool类中的apply函数和apply_async函数的区别
2023-03-21 20:23:37
![](https://img.aspxhome.com/file/2023/0/81860_0s.png)
Vue2 配置 Axios api 接口调用文件的方法
2024-05-05 09:08:37
![](https://img.aspxhome.com/file/2023/0/130840_0s.jpg)
Python基于Opencv识别两张相似图片
2021-01-13 20:16:42
![](https://img.aspxhome.com/file/2023/6/70786_0s.jpg)
python 网络编程要点总结
2023-09-30 06:15:38
[组图]手把手教你制作ASP留言本
2007-09-22 09:32:00
![](https://img.aspxhome.com/file/UploadPic/up/2007092210284443.jpg)
Python的type函数结果你知道嘛
2023-01-07 11:33:51
有关于IE8 Beta 1两个提醒
2008-05-15 12:32:00
Python实现笑脸检测+人脸口罩检测功能
2022-06-24 04:01:49
![](https://img.aspxhome.com/file/2023/4/87474_0s.png)
用Vue Demi同时支持Vue2和Vue3的方法
2024-05-13 09:38:35
![](https://img.aspxhome.com/file/2023/9/125279_0s.png)
基于python判断字符串括号是否闭合{}[]()
2022-03-25 15:58:45
Python 分形算法代码详解
2023-05-28 04:18:51
![](https://img.aspxhome.com/file/2023/8/128338_0s.jpg)
python通配符之glob模块的使用详解
2021-07-16 23:13:18
Python制作exe文件简单流程
2022-06-07 01:11:12
![](https://img.aspxhome.com/file/2023/2/91852_0s.png)
pycharm实现设置自动的参数注释标识
2023-11-25 10:26:23
![](https://img.aspxhome.com/file/2023/3/127113_0s.jpg)
flask框架实现连接sqlite3数据库的方法分析
2024-01-21 08:52:38
在docker上安装运行mysql实例
2024-01-19 10:44:26
该死的IE,走好
2009-01-15 12:26:00
![](https://img.aspxhome.com/file/UploadPic/20091/15/byebye_ie6-71s.png)