Python3中global/nonlocal用法
全局变量(global variable)是那些未在任何函数内部定义并且具有全局作用域的变量,而局部变量(local variable)是那些在函数内部定义并且其作用域仅限于该函数的变量。换句话说,我们可以说局部变量只能在初始化它的函数内部访问,而全局变量在整个程序和每个函数内部都可以访问。
global关键字:如果我们要进行赋值或更改全局变量,我们只需要在函数中使用global关键字。打印和访问全局变量不需要global关键字。如果在函数内部更改或创建的任何变量尚未声明为全局变量,则它都是局部变量。在函数外使用global关键字无效。global绑定全局变量。
nonlocal关键字:与global关键字功能相似,但用于嵌套函数(nested function)中。nonlocal绑定局部变量,只对局部起作用,离开嵌套函数,那么该变量则无效。
以上内容主要参考:https://www.geeksforgeeks.org/global-local-variables-python/
以下为测试代码:
var = 6if var == 1:# reference: https://www.geeksforgeeks.org/global-local-variables-python/def f(): # Creating local variabless = "I love Geeksforgeeks" # local vairableprint("Inside Function:", s)f()#print("s:", s) # NameError: name 's' is not defined
elif var == 2:# reference: https://www.geeksforgeeks.org/global-local-variables-python/# Defining and accessing global variablesdef f(): # This function uses global variable sprint("Inside Function:", s)# Global scopes = "I love Geeksforgeeks" # global variable, is used both inside the f function as well as outside the f functionf()print("Outside Function:", s)
elif var == 3:# reference: https://www.geeksforgeeks.org/global-local-variables-python/# This function has a variable with name same as sdef f():#s += 'GFG' # UnboundLocalError: local variable 's' referenced before assignments = "Me too." # 如果在函数作用域内也定义了同名变量,那么它将仅打印函数内部给出的值,而不是全局值print(s)s = "I love Geeksforgeeks" # global scopef()print(s) # I love Geeksforgeeks
elif var == 4:# reference: https://www.geeksforgeeks.org/global-local-variables-python/# This function modifies the global variable 's'def f():global s # 如果我们要进行赋值或更改全局变量,我们只需要在函数中使用global关键字s += ' GFG'print(s)s = "Look for Geeksforgeeks Python Section"print(s)s = "Python is great!" # global scopef()print(s) # Look for Geeksforgeeks Python Section
elif var == 5:# reference: https://www.geeksforgeeks.org/use-of-nonlocal-vs-use-of-global-keyword-in-python/def fun():var1 = 10def gun():nonlocal var1 # tell python explicitly that it has to access var1 initialized in fun using the keyword nonlocal# global var1; var1 = var1 + 10 # NameError: name 'var1' is not definedvar1 = var1 + 10print(var1) # 20gun()print(var1) # 20fun()
elif var == 6:# reference: https://www.geeksforgeeks.org/python-nonlocal-keyword/def geek_func():geek_name = "geekforgeeks" # local variable to geek_funcdef geek_func1(): # First Inner functiongeek_name = "GeekforGeeks"def geek_func2(): # Second Inner functionnonlocal geek_name # Declairing nonlocal variablegeek_name = 'GEEKSFORGEEKS'print(geek_name) # Printing our nonlocal variable, GEEKSFORGEEKSgeek_func2() # Calling Second inner functiongeek_func1() # Calling First inner functionprint(geek_name) # Printing local variable to geek_func, geekforgeeksgeek_func()
print("test finish")
GitHub:https://github.com/fengbingchun/Python_Test
Python3中global/nonlocal用法相关推荐
- Python3 中的nonlocal用法
nonlocal是在Python3.2之后引入的一个关键字,它是用在封装函数中的.百度两者区别讲的也不清楚,用法还是没说清楚,查看官方文档,更是晦涩难懂,所以在此做一下学习笔记. 我先说一下官网的no ...
- python中global的用法
python变量的作用域: Local 局部作用域 Enclosing 闭包函数外的函数中 Global全局作用域 查找规则:以Local->Enclosing ->Global规则查找, ...
- python3中map的用法_python3内置函数map
map是Python的内置函数, 使用的方式如下; list = map(func, iter) 其中, func是函数, iter是可迭代的序列. 它的功能是:将一个序列中的每一个元素应用传入的函数 ...
- python3中urlopen_Python3 urlopen()用法示例
对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! 一. 简介 urllib.request.urlopen()函数用于实现对目标url的访问. 函数 ...
- python3中 operator模块用法介绍
文章目录 概述 将运算符映射到函数 1基本方法 介绍 2 三个类介绍 2-1 attrgetter 介绍 2-2 itemgetter 使用介绍 1 用来排序 2 通过 获取多个值 2-3 metho ...
- Matlab 中 global 全局变量用法
用法: 在主函数里面,你需要设置 a 这个变量是一个全局变量,就需要声明一下: global a; 然后在子函数里面你又用到了 a 这个全局变量,你需要在子函数里面再次声明: global a; 这样 ...
- Python2和Python3中@abstractmethod的用法
抽象方法: 抽象方法表示基类的一个方法,没有实现,所以基类不能实例化,子类实现了该抽象方法才能被实例化. Python的abc提供了@abstractmethod装饰器实现抽象方法,下面以Python ...
- python中zipfile的使用_详解python3中zipfile模块用法
一.zipfile模块的简述 zipfile是python里用来做zip格式编码的压缩和解压缩的,由于是很常见的zip格式,所以这个模块使用频率也是比较高的, 在这里对zipfile的使用方法做一些记 ...
- Python3中的enumerate用法详解
1.函数功能讲解 enumerate()是python的内置函数.适用于python2.x和python3.x enumerate在字典上是枚举.列举的意思 enumerate参数为可遍历/可迭代的对 ...
最新文章
- MaxCompute助力北斗大数据,千寻位置3秒实现厘米级定位
- wxWidgets:wxKeyEvent类用法
- LiveJournal发展历程
- Python3中的map与reduce的用法
- linux cat 文件合并,linux cat两个文件是肿么合并的
- 如何把pdf转换成ezd_pdf怎么转换成word怎样编辑
- 好吧,我承认我是爱瞎折腾----利用YDUI改变页面UI
- 《韩立刚计算机网络》第一章
- 网络信息安全知识框架
- 『纪念册 · 转专业任务』
- mysql 备份 access_备份access数据库
- [渝粤教育] 西南科技大学 计算机文化基础复习资料
- 如何在TOMCAT上安装Liferay
- 金庸群侠转2完整攻略(Flash)
- 火车没有方向盘操纵转向,如何实现换轨?看完涨知识了
- 情人节相关的公众号图文这样排版,看过的都说美!
- for the love,for the dream
- docker run --privileged参数(容器权限全开,不利于宿主机安全,宿主机容易重启)(与/usr/sbin/init共用)
- mysql, mysqladmin, mysqld之间的区别。
- 5.03GEN-B发布!PSP 2000v3/3000最新自制系统
热门文章
- Computer Vision Tasks
- dist包编译html_gulp4 多页面项目管理打包(html, es6,less编译压缩版本控制)
- OpenCV 遇到的问题
- 使用SCSS高亮显示控件、聚焦位置
- 【实用快捷键】设置WebStorm中Show in Explorer(在资源管理器中打开)快捷键Alt+Shift+R(类似VSCode)
- 一道题弄明白二维数组的指针
- WCDMA系统中的扰码规划
- 使用ubuntu(18.04) 作为软路由器连接互联网
- 自己开发开源jquery插件--给jquery.treeview加上checkbox
- Visual Studio 2005 Team System下载地址