[英]I am having trouble in Python - from import does not working
I am trying to import from a specific python file (which I wrote) class that in that file and it seems that python just does not recognize my file.我正在尝试从该文件中的特定 python 文件(我写的)class 导入,似乎 python 只是无法识别我的文件。 add image to represent the situation more deeply: that the file I want to import the Ball class from:
添加图像以更深入地表示情况:我要从以下位置导入 Ball class 的文件:
the main file and the error:主文件和错误:
To import from the same directory, put a dot at the front of the module name like:要从同一目录导入,请在模块名称前面添加一个点,例如:
from .shapes import Ball
But if you are running main_Pygame.py as the script then this will not work.但是,如果您将 main_Pygame.py 作为脚本运行,那么这将不起作用。 You should create a subdirectory for shapes.py, say
mylib
and then make an empty file called __init__.py
there and mve shapes.py to that directory.您应该为shapes.py 创建一个子目录,比如
mylib
,然后在其中创建一个名为__init__.py
的空文件,并将shapes.py 移动到该目录。 Then import like:然后像这样导入:
from mylib.shapes import Ball
The __init__.py
file tells python that the mylib
directory (or whatever else you wish to call the directory) is part of the directory tree it should look for modules under. __init__.py
文件告诉 python mylib
目录(或您希望调用的任何其他目录)是它应该在其下查找模块的目录树的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.