[英]Python - Global variable not passing through to function
def fun1():
print x
import DefTest
x = 1
DefTest.fun()
為什么在執行 test.py 時出現“NameError: global name 'x' is not defined”? 我該如何正確設置它以便我可以抓住這個 function
每個模塊都有自己的全局fun
使用DefTest.x
,而不是test.x
>>> import DefTest
>>> DefTest.x = 5
>>> DefTest.fun()
5
您可能認為以下內容也有效
from DefTest import x
x = 5
DefTest.fun()
但事實並非如此,因為from DefTest import x
在模塊test
中創建了一個新的全局變量,該變量使用DefTest.x
創建DefTest.x
別名”。
在 test.py 中,使用完全限定名稱: deftest.x = 1
def fun1():
print x
import DefTest
x = 1
DefTest.fun()
為什么我在執行 test.py 時得到“NameError: global name 'x' is not defined”? 如何正確設置它以便我可以抓住這個 function
您應該在 test.py 文件中將變量名稱 x 與 Package DefTest 一起傳遞
DefTest.x = 1
DefTest.func1()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.