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

最新文章

  1. [Android]依赖注入框架squareup的dagger
  2. 将Jquery序列化后的表单值转换成Json
  3. mac 安装 php nginx mysql
  4. Ext.Net 破解
  5. Repeater上下排序按钮
  6. UVaLive 6855 Banks (水题,暴力)
  7. LINUX系统怎么关闭防火墙?
  8. Linux下高效编写Shell——shell特殊字符汇总
  9. AS3 Graphics 多次绘制
  10. Android WebView简介
  11. ASP.NET 委托,异步调用例子 .
  12. MySQL编程基础
  13. 转义字符\(在hive+shell以及java中注意事项):正则表达式的转义字符为双斜线,split函数解析也是正则
  14. Mac下多版本JDK安装
  15. STM32外设初始化步骤
  16. PV原语操作详解
  17. apache服务器伪静态配置说明
  18. Grand Central Dispatch
  19. Access与SQL Server 语法差异
  20. compile——生成ast

热门文章

  1. stm32 development
  2. monkey自定义脚本
  3. 安装tidb数据库
  4. /usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependency
  5. Centos修改IP的两种方式
  6. excel匹配相应条件 自动填充数据
  7. jdbc.properties不能加载到tomcat项目下面
  8. 前端要懂的nginx配置
  9. C# 计时函数(毫秒)
  10. Spring MVC 面试题