我在一個更簡單的檔案中重新創建了這個錯誤。
主檔案
from funcA import *
test()
print(x)
函式A.py
def test():
global x
y = 2
return x
我收到“NameError: name 'x' is not defined”,我錯過了什么?
uj5u.com熱心網友回復:
from funcA import *創建一個在全域范圍內命名的新變數。它的初始值來自,但它是一個未鏈接到 的獨特變數。xmain.pyfuncA.xfuncA.x
當您呼叫 時test,您會更新 的值funcA.x,但main.x保持不變。
呼叫之后test,funcA.x直接查看就可以看到變化了。
from funcA import *
import funcA
test()
print(funcA.x)
uj5u.com熱心網友回復:
您必須在函式之外創建一個全域變數。
該global關鍵字不能使用這樣的。
必須x在函式之外。
# funcA.py
x = "something"
def test():
global x
y = 2
return x
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/320742.html
上一篇:顫振不能改變變數的值
下一篇:顫振無法訪問靜態變數
