python中global与nonlocal比较

yipeiwu_com5年前Python基础

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())

二、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())

也可以使用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

相关文章

python嵌套函数使用外部函数变量的方法(Python2和Python3)

python嵌套函数使用外部函数变量的方法,Python2和Python3均可使用 python3 def b(): b = 1 def bchange(): nonlo...

python多线程分块读取文件

本文实例为大家分享了python多线程分块读取文件的具体代码,供大家参考,具体内容如下 # _*_coding:utf-8_*_ import time, threading, C...

用Python实现通过哈希算法检测图片重复的教程

用Python实现通过哈希算法检测图片重复的教程

Iconfinder 是一个图标搜索引擎,为设计师、开发者和其他创意工作者提供精美图标,目前托管超过 34 万枚图标,是全球最大的付费图标库。用户也可以在 Iconfinder 的交易板...

PyTorch基本数据类型(一)

PyTorch基本数据类型(一)

PyTorch基础入门一:PyTorch基本数据类型 1)Tensor(张量) Pytorch里面处理的最基本的操作对象就是Tensor(张量),它表示的其实就是一个多维矩阵,并有矩阵相...

python编程实现归并排序

python编程实现归并排序

因为上个星期leetcode的一道题(Median of Two Sorted Arrays)所以想仔细了解一下归并排序的实现。 还是先阐述一下排序思路: 首先归并排序使用了二分法,归根...