簡體   English   中英

在 function 中定義之前使用“全局”關鍵字會發生什么?

[英]What happens when using 'global' keyword before defining inside a function?

我是 Python 的初學者,最近才遇到“全局”關鍵字。 我了解“全局”更改變量的 scope 的基本用法,但我想知道為什么以下代碼不起作用:

def foo():
    global y
    print('y inside foo is', y)

foo()
print('global y is', y)

我假設它會輸出一些空變量,例如 None,但是它給出了:

NameError: name 'y' is not defined

我試過了:

def foo():
    global y
    y = 1
    print('y inside foo is', y)

foo()
print('global y is', y)

這給出了:

y inside foo is 1
global y is 1

這是意料之中的,因為我們首先聲明有一個全局變量 y,然后給它賦值 1,所以我們在 globals() 中找到它。

另一個問題是:

def foo():
    def bar():
        print(locals())
        print(y)
    y = 1
    bar()
foo()

給出:

{'y': 1}
1

因為在 bar() 內部,我們有一個局部變量 'y'。

但是當我將局部變量“y”更改為:

def foo():
    def bar():
        print(locals())
        y = y + 1
        print(y)
    y = 1
    bar()
foo()

print(locals()) 輸出 {},我不明白為什么。

您永遠不會將y定義為實際包含一個值。 在 Python 中,嘗試訪問沒有值的變量會引發NameError ,您將在此處看到。 您可以初始化變量以啟動(使用None或其他一些首選默認值),然后通過文件的 rest 使用它,如下所示:

y = None
def foo():
    global y
    print('y inside foo is', y)

foo()
print('global y is', y)

foo 里面的 y 是 None
全局 y 為無

示例 1:Python 中的“空變量”是什么? 你從來沒有定義過y 你被打了。

例二:你懂的

示例 3:不, bar沒有局部變量y 由於沒有,它通過其上下文堆棧向外搜索,並在下一個名稱空間foo中找到y

示例 4: locals確實是空的。 y是本地的foo ,而不是bar 但是,您的增量語句錯誤,因為嘗試更改y意味着您有一個global y (您沒有),或者您正在定義一個新的。 因此,RHS y必須是本地的——但尚未定義,你會再次受到打擊。

當 Python 創建 function 它掃描它的身體時,每件事都會發生:

def foo():
    def bar():
        print(locals())  # P is not present
        print(y)
        print(y)
        x = 5
        print(locals())  # after initializing x is added to local
    y = 1
    p = 1
    # ('x',) local variables
    print(bar.__code__.co_varnames)
    # ('y',)  non local variables used by the function
    print(bar.__code__.co_freevars)
    bar()
foo()

Python 發現bar使用了y但它沒有在主體 function 的任何點初始化,所以它是co_freevars

co_freevars:自由變量名稱的元組(通過函數的閉包引用

分配表達式左側的其他變量是co_varnames

co_varnames:arguments 和局部變量的名稱元組

當您使用 global 時,您是在告訴 Python 這不是局部變量,並且當您更改它的值時,您會在 function 被定義的全局空間中更改它,而不是在它被調用的地方。

def foo():
    global y  # assumes that y exist in the current module
    y = 5  # when you change it's value it change the value of y in the current module

# even that we used `y` in a left side of assignment expression is not added as local variable
print(foo.__code__.co_varnames)

當您在未定義變量y的模塊中定義foo時, foo不會在該模塊的全局 scope 中找到該變量,這就是您得到: NameError: name 'y' is not defined

要了解更多角色global關鍵字,請檢查:

def foo():
    global y
    y = 1  # this set the variable in the scope of module not the scope of this function
    print('y' in locals())  # False it's not a local variable of this method


print('y' in globals())  # False
foo()
print('y' in globals())   # True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM