[英]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.