在Python什么是一个全球性的声明?(In Python what is a global sta

2019-07-05 07:50发布

什么是一个全球性的声明 ? 以及如何使用它? 我已阅读Python的官方定义 ;
然而,它没有很多道理给我。

Answer 1:

在python每“可变的”被限制到一定范围。 一个python“文件”的范围是模块范围。 考虑以下:

#file test.py
myvariable = 5  # myvariable has module-level scope

def func():
    x = 3       # x has "local" or function level scope.

本地范围的对象,一旦死去的函数退出,无法再恢复(除非你return它们),但在一个函数中,您可以访问在模块级范围(含任何范围或变量):

myvariable = 5
def func():
    print(myvariable)  # prints 5

def func2():
    x = 3
    def func3():
        print(x)       # will print 3 because it picks it up from `func2`'s scope

    func3()

但是,你不能对参考使用赋值,并期望它会传播到外部范围:

myvariable = 5
def func():
    myvariable = 6     # creates a new "local" variable.  
                       # Doesn't affect the global version
    print(myvariable)  # prints 6

func()
print(myvariable)      # prints 5

现在,我们终于到了global 。 在global关键词是,你告诉你的功能的特定变量是在全局(模块级)范围内定义蟒蛇的方式。

myvariable = 5
def func():
    global myvariable
    myvariable = 6    # changes `myvariable` at the global scope
    print(myvariable) # prints 6

func()
print(myvariable)  # prints 6 now because we were able 
                   # to modify the reference in the function

换句话说,你可以改变的值myvariable在模块范围从内部func如果使用global关键字。


顺便说一句,范围可以嵌套任意深度:

def func1():
    x = 3
    def func2():
        print("x=",x,"func2")
        y = 4
        def func3():
            nonlocal x  # try it with nonlocal commented out as well.  See the difference.
            print("x=",x,"func3")
            print("y=",y,"func3")
            z = 5
            print("z=",z,"func3")
            x = 10

        func3()

    func2()
    print("x=",x,"func1")

func1()

现在,在这种情况下,没有一个变量都在全球范围内宣布,并在python2,不存在(易/干净)的方式来改变的值x的范围func1从内部func3 。 这就是为什么nonlocal关键字在python3.x介绍。 nonlocal是扩展global ,使您可以修改您在任何范围内它是从另一个拉到范围拿起一个变量。



Answer 2:

mgilson做了很好的工作,但我想补充一些。

list1 = [1]
list2 = [1]

def main():
    list1.append(3)
    #list1 = [9]
    list2 = [222]

    print list1, list2


print "before main():", list1, list2
>>> [1] [1]
main()
>>> [1,3] [222]
print list1, list2    
>>> [1, 3] [1]

在函数里,Python的假设,除非你把它声明为全球每一个变量,局部变量,或者你正在访问一个全局变量。

list1.append(2) 

因为你是访问“列表1”和列表是可变的是可能的。

list2 = [222]

因为你是初始化一个局部变量是可能的。

不过,如果你取消注释#列表1 = [9],你会得到

UnboundLocalError: local variable 'list1' referenced before assignment

这意味着你正试图初始化一个新的局部变量“列表1”,但它已经被引用之前,你都出了范围的重新分配它。

要输入范围,申报“列表1”作为全球性的。

我强烈建议你阅读这即使是在最后一个错字。



Answer 3:

基本上,它告诉它给出的变量应该被修改或者被分配在全球范围内,而不是默认的地方一级的解释。



Answer 4:

a = 1

def f():
    a = 2 # doesn't affect global a, this new definition hides it in local scope

a = 1

def f():
    global a
    a = 2 # affects global a


Answer 5:

您可以通过声明为在修改它的每个功能的全球使用其他功能的全局变量

Python的希望,以确保你真的知道这是你通过明确要求全球关键字玩什么。

见这个答案



文章来源: In Python what is a global statement?
标签: python global