• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > python中global与nonlocal比较

python中global与nonlocal比较

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python nonlocal,python中nonlocal,nonlocal,nonlocal means,nonlocal screening等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量

一、global

global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。

gcount = 0

def global_test():
    print (gcount)
   
def global_counter():
    global gcount
    gcount +=1
    return gcount
   
def global_counter_test():
    print(global_counter())
    print(global_counter())
    print(global_counter())
</div>

二、nonlocal

nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter
   
def make_counter_test():
  mc = make_counter()
  print(mc())
  print(mc())
  print(mc())
</div>

也可以使用generator来实现类似的counter。如下:

def counter_generator():
    count = 0
    while True:
        count += 1
        yield count
   
def counter_generator_test():
  # below is for python 3.x and works well
  citer = counter_generator().__iter__()
  i = 0
  while(i < 3) :
    print(citer.__next__())
    i+=1
 
def counter_generator_test2(): 
  #below code don't work
  #because next() function still suspends and cannot exit
  #it seems the iterator is generated every time.
  j = 0
  for iter in counter_generator():
    while(j < 3) :
      print(iter)
      j+=1
</div>

</div>

您可能想查找下面的文章:

  • Python中关键字nonlocal和global的声明与解析
  • python中global与nonlocal比较
  • python中global与nonlocal比较

相关文章

  • Python实现栈的方法
  • Python去除字符串两端空格的方法
  • Using Django with GAE Python 后台抓取多个网站的页面全文
  • python集合类型用法分析
  • Python中的特殊语法:filter、map、reduce、lambda介绍
  • Python的requests网络编程包使用教程
  • Python缩进和冒号详解
  • Python中的pass语句使用方法讲解
  • python抓取京东商城手机列表url实例代码
  • python sort、sorted高级排序技巧

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python 基于Twisted框架的文件夹网络传输源码
    • Python最长公共子串算法实例
    • Django的信号机制详解
    • 深入了解Python数据类型之列表
    • 浅析python 内置字符串处理函数的使用方法
    • 举例讲解Python中的list列表数据结构用法
    • Python字符串转换成浮点数函数分享
    • 使用Python脚本来控制Windows Azure的简单教程
    • Python字符串的encode与decode研究心得乱码问题解决方法
    • python将图片文件转换成base64编码的方法

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有