Python变量作用域问题
发布日期:2022-03-18 18:19:13
浏览次数:2
分类:技术文章
本文共 551 字,大约阅读时间需要 1 分钟。
本文最后更新于2018-6-20,可能会因为没有更新而失效。如已失效或需要修正,请联系我!
今天在用Python写程序时突然想起了Python变量作用域的问题,代码如下:
def run(): global x x=3 print(x)run()x+=1print(x)
这段代码运行并不会出错,问题的关键主要在于global这个关键字,stackoverflow上有人问过类似的问题,
主要的意思是在一个函数里如果把一个变量声明为global,那么这个变量就是全局的, 如果全局变量中不存在这个变量,那就新建一个全局变量。 然后我就写了另外一段有意思的代码:#main.pyimport main2main2.first()main2.then()
#main2.pydef first(): global x x=0 print(x)def then(): global x x+=1 print(x)
这是在2个文件里的Python代码,可以正确运行。
这段代码的意思是Python的global声明的最大作用域是当前文件,并不能用其他文件里的全局变量。 在上面的代码中x的作用域是main2整个文件,而在main里是没有x这个变量存在的!转载地址:https://zhang0peter.blog.csdn.net/article/details/83419070 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月07日 01时32分37秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
sqlite学习
2019-04-27
手把手教你实现Unity与Android的交互
2019-04-27
手把手教你使用Unity的Behavior Designer
2019-04-27
Unity3D摄像机裁剪——NGUI篇
2019-04-27
lua深拷贝一个table
2019-04-27
app运行提示Unable to Initialize Unity Engine
2019-04-27
spring boot 与 Ant Design of Vue 实现修改按钮(十七)
2019-04-27
spring boot 与 Ant Design of Vue 实现删除按钮(十八)
2019-04-27
spring boot 与 Ant Design of Vue 实现新增角色(二十)
2019-04-27
spring boot 与 Ant Design of Vue 实现修改角色(二十一)
2019-04-27
spring boot 与 Ant Design of Vue 实现删除角色(补二十一)
2019-04-27
spring boot 与 Ant Design of Vue 实现左侧组织树(二十三)
2019-04-27
spring boot 与 Ant Design of Vue 实现新增组织(二十四)
2019-04-27
spring boot 与 Ant Design of Vue 实现修改组织(二十五)
2019-04-27
spring boot 与 Ant Design of Vue 实现删除组织(二十六)
2019-04-27
spring boot 与 Ant Design of Vue 实现删除用户(三十)
2019-04-27