python修改全局变量可以不加global吗?
作者:侯小啾?? 时间:2021-01-11 08:10:56
以如下代码为例,我们在局部作用域内使用全局变量a,需要使用global
关键字进行声明。否则代码会不可用。
a = 100
def fun():
global a
a += 100
fun()
print(a)
但是也有一种常见的情况,
可以修改的数据类型在函数内部做修改操作是不需要声明global的:
list1 = [100, 200]
def fun():
list1.append(300)
fun()
print(list1)
但是如果把添加元素的命令换成列表拼接的方式:
list1 += list1 + [300]
则代码依然不可用,需要添加关键字global
声明list1才可用。
进一步展开说:
list1 = [100, 200]
print(list1, id(list1))
list1 = list1 + [300]
print(list1, id(list1))
list1 += [400]
print(list1, id(list1))
list1.append(500)
print(list1, id(list1))
对于list1 = list1 + [300]
如图,list1 = list1 + [300]
改变了list1的id,这意味着,得到的新的list1已经不是原来的list1变的,而是重新生成的,也可以理解成是重新赋值的list1,只是过程中利用了list1。该代码在局部作用域没有global不可用,因为在生成新的变量之前, list1 + [300] 中的list1是取不到的。
list1 += [400],list1.append(500)
都不改变id,改变的是原变量list1。
但是list1 += [400]
无global不可用,原因同上述情况一样;list1.append(500)
则无global也可用,符合 可用修改的数据类型在函数内部的修改操作不需声明global。
来源:https://skylarkprogramming.blog.csdn.net/article/details/122771338
标签:python,修改,全局变量,global
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python的几个高级语法概念浅析(lambda表达式闭包装饰器)
2021-08-07 14:18:45
在Python中操作文件之read()方法的使用教程
2021-10-28 19:23:46
详解tensorflow载入数据的三种方式
2023-07-22 19:35:56
![](https://img.aspxhome.com/file/2023/4/62904_0s.jpg)
python函数运行内存时间等性能检测工具
2021-04-08 02:24:00
![](https://img.aspxhome.com/file/2023/1/93801_0s.png)
Python基于opencv实现的简单画板功能示例
2021-05-06 20:04:37
![](https://img.aspxhome.com/file/2023/7/93447_0s.gif)
利用tkinter改变下拉列表(Combobox)的选项值
2023-07-20 03:10:37
Flume监听oracle表增量的步骤详解
2023-07-20 00:39:32
验证码-挑战你的智慧
2008-09-10 13:08:00
![](https://img.aspxhome.com/file/UploadPic/20089/10/2008910131428605s.jpg)
Python全面解读高级特性切片
2021-06-05 14:23:13
隐藏修改文件时间和文件属性的ASP脚本
2011-03-17 11:15:00
python将字符串转换成数组的方法
2021-03-04 20:09:54
K最近邻算法(KNN)---sklearn+python实现方式
2023-09-14 15:29:31
![](https://img.aspxhome.com/file/2023/9/90769_0s.jpg)
pycharm 配置svn的图文教程(手把手教你)
2022-10-21 18:47:47
![](https://img.aspxhome.com/file/2023/7/83697_0s.jpg)
Css Reset(复位)整理
2008-09-09 21:58:00
Microsoft SQL Server 2000安装问题集锦
2008-12-10 14:26:00
从客户端提升SQL Server数据库性能
2009-03-06 14:27:00
解析:轻松掌握 字符串文字字符集和校对
2008-12-17 17:07:00
网页设计进阶之一 (步骤和大局观)
2008-08-23 10:39:00
Golang 高效排序数据详情
2023-06-23 08:23:41
![](https://img.aspxhome.com/file/2023/6/87626_0s.jpg)
详解Python中的type和object
2021-03-25 13:00:58
![](https://img.aspxhome.com/file/2023/1/67921_0s.png)