更新时间:2023-12-05 13:55:40
问题是您正在script.py
内部运行custom.class2
,这意味着在运行custom.class2
时,您仍位于root
目录中
The problem is that you are running custom.class2
inside of script.py
, which means while running custom.class2
, you are still in the root
directory.
要解决此问题,应将class2.py
中的from class1 import Class1
替换为from custom.class1 import Class1
.
To fix this, you should replace from class1 import Class1
from class2.py
with from custom.class1 import Class1
.
如果您需要能够从任何工作目录中运行文件,则可以用以下内容替换其内容:
If you need to be able to run the file from any working directory, you may replace it's contents with this:
import os
import sys
path = os.path.abspath(os.path.dirname(__file__))
if not path in sys.path:
sys.path.append(path)
from class1 import Class1
class Class2():
def __init__(self):
cl1 = Class1()
print('Class2')
if __name__ == '__main__':
cl2 = Class2()
代码将文件的路径添加到sys.path
列表中,该列表包含可从中导入模块的不同路径.
The code adds the file's path in to the sys.path
list, which holds different paths from which you can import modules.