为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喵时光机 2022-12-27 16:36:09
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 ....


查看完整回答
反对 回复 2022-12-27
  • 1 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号