Test.py:def test(): print("Hello World")test()當我使用解釋器(ctrl+shift+p > Python:選擇解釋器 > 目標解釋器)運行它時,它起作用了。如果我隨后嘗試運行 repl (ctrl+shift+p > Python: Start REPL),我會看到 repl 在終端中啟動:PS C:\Development\personal\python\GettingStarted> & c:/Development/personal/python/GettingStarted/.venv/Scripts/python.exePython 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> 但是,如果我嘗試在 repl 中執行定義的方法,我會得到一個未定義的錯誤:>>> test() Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'test' is not defined
1 回答

Smart貓小萌
TA貢獻1911條經驗 獲得超7個贊
導入和使用的正確方法#1:
>>> import test
Hello World
>>> test.test()
Hello World
導入和使用的正確方法 #2:
>>> from test import test
Hello World
>>> test()
Hello World
如果您在ImportError上面的兩種方式中都得到了一個 for,那么您正在從錯誤的目錄運行 Python REPL。
文件名和函數名相同有點令人困惑。
test()在文件末尾調用 也有點不尋常(導致在導入時調用該函數)。通常它被包裝起來if __name__ == '__main__': test(),以避免在import時間調用,但在從命令行作為腳本運行時進行調用。
Import test不起作用,因為 Python 關鍵字是小寫字母且區分大小寫。
from test import Test不起作用,因為 Python 標識符(例如函數名稱)區分大小寫。
import Test可能適用于 Windows(但不適用于 macOS、Linux 和許多其他操作系統),因為 Windows 上的文件名不區分大小寫。
import test.py不起作用,因為不允許將.py擴展名作為導入模塊名稱的一部分。
import test from test不起作用,因為from ...必須在import ....
添加回答
舉報
0/150
提交
取消