簡體   English   中英

Python - 全局變量未傳遞到 function

[英]Python - Global variable not passing through to function

DefTest.py

def fun1():
    print x

測試.py

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

DefTest.py

def fun1():
    print x

測試.py

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.

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