Python3中global/nonlocal用法

      全局变量(global variable)是那些未在任何函数内部定义并且具有全局作用域的变量,而局部变量(local variable)是那些在函数内部定义并且其作用域仅限于该函数的变量。换句话说,我们可以说局部变量只能在初始化它的函数内部访问,而全局变量在整个程序和每个函数内部都可以访问。

      global关键字:如果我们要进行赋值或更改全局变量,我们只需要在函数中使用global关键字。打印和访问全局变量不需要global关键字。如果在函数内部更改或创建的任何变量尚未声明为全局变量,则它都是局部变量。在函数外使用global关键字无效。global绑定全局变量。

      nonlocal关键字:与global关键字功能相似,但用于嵌套函数(nested function)中。nonlocal绑定局部变量,只对局部起作用,离开嵌套函数,那么该变量则无效。

      以上内容主要参考:https://www.geeksforgeeks.org/global-local-variables-python/

      以下为测试代码:

var = 6

if var == 1:
    # reference: https://www.geeksforgeeks.org/global-local-variables-python/
    def f(): # Creating local variables
        s = "I love Geeksforgeeks" # local vairable
        print("Inside Function:", s)

    f()
    #print("s:", s) # NameError: name 's' is not defined
elif var == 2:
    # reference: https://www.geeksforgeeks.org/global-local-variables-python/
    # Defining and accessing global variables
    def f(): # This function uses global variable s
        print("Inside Function:", s)

    # Global scope
    s = "I love Geeksforgeeks" # global variable,  is used both inside the f function as well as outside the f function
    f()
    print("Outside Function:", s)
elif var == 3:
    # reference: https://www.geeksforgeeks.org/global-local-variables-python/
    # This function has a variable with name same as s
    def f():
        #s += 'GFG' # UnboundLocalError: local variable 's' referenced before assignment
        s = "Me too." # 如果在函数作用域内也定义了同名变量,那么它将仅打印函数内部给出的值,而不是全局值
        print(s)

    s = "I love Geeksforgeeks" # global scope
    f()
    print(s) # I love Geeksforgeeks
elif var == 4:
    # reference: https://www.geeksforgeeks.org/global-local-variables-python/
    # This function modifies the global variable 's'
    def f():
        global s # 如果我们要进行赋值或更改全局变量,我们只需要在函数中使用global关键字
        s += ' GFG'
        print(s)
        s = "Look for Geeksforgeeks Python Section"
        print(s)

    s = "Python is great!" # global scope
    f()
    print(s) # Look for Geeksforgeeks Python Section
elif var == 5:
    # reference: https://www.geeksforgeeks.org/use-of-nonlocal-vs-use-of-global-keyword-in-python/
    def fun():
        var1 = 10

        def gun():
            nonlocal var1 # tell python explicitly that it has to access var1 initialized in fun using the keyword nonlocal
            # global var1; var1 = var1 + 10 # NameError: name 'var1' is not defined
            var1 = var1 + 10
            print(var1) # 20

        gun()
        print(var1) # 20

    fun()
elif var == 6:
    # reference: https://www.geeksforgeeks.org/python-nonlocal-keyword/
    def geek_func():
        geek_name = "geekforgeeks" # local variable to geek_func

        def geek_func1(): # First Inner function
            geek_name = "GeekforGeeks"

            def geek_func2(): # Second Inner function
                nonlocal geek_name # Declairing nonlocal variable
                geek_name = 'GEEKSFORGEEKS'
                print(geek_name) # Printing our nonlocal variable, GEEKSFORGEEKS

            geek_func2() # Calling Second inner function

        geek_func1() # Calling First inner function
        print(geek_name) # Printing local variable to geek_func, geekforgeeks

    geek_func()
print("test finish")

      GitHubhttps://github.com/fengbingchun/Python_Test

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Pythonglobalnonlocal可以让你在函数内部使用和更改全局变量和外部作用域的变量。Globalglobal用于在函数内部声明全局变量,即使在函数内部也可以访问该变量。例如:x = "global" def foo(): global x x = "local" print("x inside :", x) foo() print("x outside:", x)结果:x inside : local x outside: localnonlocalnonlocal用于在函数内部修改外部作用域的变量,即使在函数内部也可以访问和修改该变量。例如:x = "global" def outer(): x = "outer" def inner(): nonlocal x x = "inner" print("x inside :", x) inner() print("x outside:", x) outer()结果:x inside : inner x outside: inner ### 回答2: globalnonlocal都是python用于在函数内部访问外部变量的关键字。 首先,我们来看一下global关键字的用法。当我们在函数内部想要修改全局变量时,需要使用global关键字。下面是一个例子: ```python x = 10 def modify_global(): global x x = 20 modify_global() print(x) # 输出为20 ``` 在这个例子,通过在函数定义内使用`global x`,我们告诉python在函数内部修改的`x`是全局变量`x`,而不是在函数内部定义的局部变量。 接下来,我们来看一下nonlocal关键字的用法。当我们在嵌套函数想要修改外部函数的局部变量时,需要使用nonlocal关键字。下面是一个例子: ```python def outer(): x = 10 def inner(): nonlocal x x = 20 inner() print(x) # 输出为20 outer() ``` 在这个例子,通过在内部函数定义内使用`nonlocal x`,我们告诉python在内部函数修改的`x`是外部函数`outer()`的局部变量,而不是在内部函数定义的局部变量。 总结一下,global关键字用于在函数修改全局变量,nonlocal关键字用于在嵌套函数修改外部函数的局部变量。 ### 回答3: global关键字和nonlocal关键字都是用于访问外部作用域的变量,但它们之间有一些关键的区别。 首先,我们先了解一下global用法。当我们在函数内部定义一个变量时,默认情况下它是局部变量,只在函数内部有效。如果需要在函数内部改变一个全局变量的值,我们就需要用到global关键字。下面是一个示例: ```python count = 0 def increment(): global count count += 1 print(count) # 输出0 increment() print(count) # 输出1 ``` 在上面的例子,我们声明了一个全局变量count,并定义了一个函数increment来增加count的值。在函数内部,我们使用global关键字告诉Python,count是一个全局变量,而不是一个局部变量。这样,在我们调用increment函数后,count的值会被成功增加。 接下来,我们来看一下nonlocal用法nonlocal关键字用于在嵌套函数访问上一级非全局作用域的变量。在Python,我们可以在函数内部定义另一个函数,这就是嵌套函数。下面是一个嵌套函数的例子: ```python def outer(): x = "hello" def inner(): nonlocal x x = "world" print("inner:", x) inner() print("outer:", x) outer() ``` 在上面的例子,我们定义了一个外部函数outer,它内部定义了一个局部变量x。然后,我们定义了一个嵌套函数inner,在inner函数内部,我们使用nonlocal关键字告诉Python,x是在外部函数定义的变量。这样,在我们调用inner函数后,x的值会被成功改变。运行上面的代码,会输出"inner: world"和"outer: world"。 综上所述,global用于访问全局作用域的变量,而nonlocal用于访问上一级非全局作用域的变量。使用这两个关键字能够更灵活地操作不同作用域的变量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值