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

相关文章

pandas 对series和dataframe进行排序的实例

本问主要写根据索引或者值对series和dataframe进行排序的实例讲解 代码: #coding=utf-8 import pandas as pd import numpy a...

python分割文件的常用方法

本文大家整理了一些比较好用的关于python分割文件的方法,方法非常的简单实用。分享给大家供大家参考。具体如下: 例子1 指定分割文件大小 配置文件 config.ini: 复制代码 代...

CentOS6.9 Python环境配置(python2.7、pip、virtualenv)

python2.7 yum install -y zlib zlib-devel openssl openssl-devel mysql-devel gcc gcc-c++ wget...

使用Python实现BT种子和磁力链接的相互转换

bt种子文件转换为磁力链接 BT种子文件相对磁力链来说存储不方便,而且在网站上存放BT文件容易引起版权纠纷,而磁力链相对来说则风险小一些。而且很多论坛或者网站限制了文件上传的类型,分享一...

使用Pandas将inf, nan转化成特定的值

使用Pandas将inf, nan转化成特定的值

1. 数据处理中很恶心,出现 RuntimeWarning: divide by zero encountered in divide 发现自己的DataFrame中有除以0的运算,出...