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

  • 相关阅读:
    POJ 1739 Tony's Tour(插头DP)
    POJ 1741 Tree(树的分治)
    POJ 1655 Balancing Act(求树的重心)
    POJ 2631 Roads in the North(求树的直径,两次遍历 or 树DP)
    codeforces 359E Neatness(DFS+构造)
    codeforces 295C Greg and Friends(BFS+DP)
    codeforces 228E The Road to Berland is Paved With Good Intentions(2-SAT)
    Eclipse 代码提示功能设置。
    svn 清空
    android 线程
  • 原文地址:https://www.cnblogs.com/yuzhanhong/p/9183161.html
Copyright © 2011-2022 走看看