猿问

为什么 Visual Studio Code 中的 Python repl 告诉我我的对象未定义?

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.exe

Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32

Type "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


喵喵时光机
浏览 138回答 1
1回答

Smart猫小萌

导入和使用的正确方法#1:>>> import testHello World>>> test.test()Hello World导入和使用的正确方法 #2:>>> from test import testHello 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 ....
随时随地看视频慕课网APP

相关分类

Python
我要回答