zoukankan      html  css  js  c++  java
  • python中global和nonlocal用法的详细说明

     

    一、global

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

     
    gcount = 0
    
    def global_test():
        gcount+=1
        print (gcount)
    global_test()
     

    以上代码会报错:第一行定义了全局变量,在内部函数中又对外部函数进行了引用并修改,那么python会认为它是一个局部变量,有因为内部函数没有对其gcount进行定义和赋值,所以报错。

    2、如果局部要对全局变量修改,则在局部声明该全局变量

     
    gcount = 0
     
    def global_test():
        global  gcount
        gcount+=1
        print (gcount)
    global_test()
     

    以上输出为:1

    3、如果局部不声明全局变量,并且不修改全局变量,则可以正常使用

    gcount = 0
     
    def global_test():
        print (gcount)
    global_test()

    以上输出为:0

     二、nonlocal

    1、 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())
     
    make_counter_test()
    

      以上输出为:

    1

    2

    3

    三、混合使用

     
    def scope_test():
        def do_local():
            spam = "local spam" #此函数定义了另外的一个spam字符串变量,并且生命周期只在此函数内。此处的spam和外层的spam是两个变量,如果写出spam = spam + “local spam” 会报错
        def do_nonlocal():
            nonlocal  spam        #使用外层的spam变量
            spam = "nonlocal spam"
        def do_global():
            global spam
            spam = "global spam"
        spam = "test spam"
        do_local()
        print("After local assignmane:", spam)
        do_nonlocal()
        print("After nonlocal assignment:",spam)
        do_global()
        print("After global assignment:",spam)
     
    scope_test()
    print("In global scope:",spam)
     

    以上输出为:

    After local assignmane: test spam
    After nonlocal assignment: nonlocal spam
    After global assignment: nonlocal spam
    In global scope: global spam

  • 相关阅读:
    我的第一个作业
    团队任务3:第一次冲刺
    课后作业3:个人项目(词频统计及其效能分析)
    课后作业2:个人项目
    一切的开始,从未有过的改变——课后作业1:准备
    Fiddler 添加IP显示、响应时间功能
    Jmeter所有结果分析
    云盘资源爬取利器 fmv
    python 中的 sys , os 模块用法总结
    Python 编写登录接口
  • 原文地址:https://www.cnblogs.com/yuzhanhong/p/9183161.html
Copyright © 2011-2022 走看看