global和nonlocal的用法
2024-10-07 02:37:39
1 nonlocal声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量.写在内部嵌套函数里面,它实质上是将该变量定义成了全局变量,它等价于用两个global来定义该变量.只不过用两个global来实现太繁琐.只用一个global的话无法在这儿(嵌套函数中)实现.
def make_counter():
global count
count = 0
def counter():
# nonlocal count
global count
count += 1
return count
return counter
mc = make_counter()
print(mc())
print(mc())
print(mc())
#
#
#
2 利用global可将函数的局部变量变为全局变量
# 全局变量在函数内部可以任意调用
hehe=6
def f():
print(hehe)
f()
print(hehe)
#
# # 注意这里在函数先输出hehe变量时,即先使用了它,后定义它是2,所以程序认为它是局部变量,会报先使用后定义的错误
hehe=6
def f():
print(hehe)
hehe=2
f()
print(hehe)
# UnboundLocalError: local variable 'hehe' referenced before assignment # 这个是先定义后使用,函数内的hehe同样是局部变量
hehe=6
def f():
hehe=2
print(hehe)
f()
print(hehe)
#
# hehe=6
def f():
global hehe
print(hehe)
hehe=3
f()
print(hehe)
#
#
参考: https://www.cnblogs.com/summer-cool/p/3884595.html
https://www.cnblogs.com/yuzhanhong/p/9183161.html
https://www.liaoxuefeng.com/wiki/1016959663602400/1017434209254976#0
https://www.cnblogs.com/tallme/p/11300822.html
最新文章
- [Android]依赖注入框架squareup的dagger
- 将Jquery序列化后的表单值转换成Json
- mac 安装 php nginx mysql
- Ext.Net 破解
- Repeater上下排序按钮
- UVaLive 6855 Banks (水题,暴力)
- LINUX系统怎么关闭防火墙?
- Linux下高效编写Shell——shell特殊字符汇总
- AS3 Graphics 多次绘制
- Android WebView简介
- ASP.NET 委托,异步调用例子 .
- MySQL编程基础
- 转义字符\(在hive+shell以及java中注意事项):正则表达式的转义字符为双斜线,split函数解析也是正则
- Mac下多版本JDK安装
- STM32外设初始化步骤
- PV原语操作详解
- apache服务器伪静态配置说明
- Grand Central Dispatch
- Access与SQL Server 语法差异
- compile——生成ast
热门文章
- stm32 development
- monkey自定义脚本
- 安装tidb数据库
- /usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependency
- Centos修改IP的两种方式
- excel匹配相应条件 自动填充数据
- jdbc.properties不能加载到tomcat项目下面
- 前端要懂的nginx配置
- C# 计时函数(毫秒)
- Spring MVC 面试题