簡體   English   中英

Python 變量聲明和 function 錯誤

[英]Python variable declaration and function error

我有一個關於 Python 的問題。

我想在 function 中使用一個變量,但出現此錯誤:

NameError: name 'BP' is not defined

這是我的代碼:

# File 1 test.py:
from importlib import import_module

def test():
    print(BP)
    print(BP["test2"].d)

if __name__ == "__main__":
    BP: (dict) = {}
    BP.update({"test2": import_module(".test2", "test_folder")})



# File 2 file2.py in test_folder:
from test import test

d: (dict) = {"Hello": "World"}

print("hi")
test()

所以我的問題是:為什么這不起作用?

關於:

if __name__ == "__main__":

僅當您實際運行test.py文件時才如此,而不是像從file2.py那樣僅導入它時才如此。 在后一種情況下,沒有運行代碼將BP變量綁定到 object,因此調用test會報錯。

暫無
暫無

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

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