python中global与nonlocal比较

yipeiwu_com6年前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进行波形及频谱绘制的方法

如下所示: # -*- coding: UTF-8 -*- import wave import numpy as np import matplotlib.pyplot as pl...

python实现按行切分文本文件的方法

本文实例讲述了python实现按行切分文本文件的方法。分享给大家供大家参考,具体如下: python脚本利用shell命令来实现文本的操作, 这些命令大大减少了我们的代码量。 比如按行切...

python获取文件扩展名的方法

本文实例讲述了python获取文件扩展名的方法。分享给大家供大家参考。具体实现方法如下: import os.path def file_extension(path): r...

pytorch点乘与叉乘示例讲解

点乘 import torch x = torch.tensor([[3,3],[3,3]]) y = x*x #x.dot(x) z = torch.mul(x,x) #x.mul...

python numpy之np.random的随机数函数使用介绍

np.random的随机数函数(1) 函数 说明 rand(d0,d1,..,dn)...