简体   繁体   English

从另一个目录导入 class

[英]Importing a class from another directory

I know this question has been asked before but none of the solutions worked for me.我知道之前有人问过这个问题,但没有一个解决方案对我有用。 So let's say I have a directory structured as follow:所以假设我有一个结构如下的目录:

folder1:
 -- file1.py
folder2:
 -- class2.py

I want to call the class from class2.py in my file1.py so what I did at the start of the file1.py is我想从我的class2.py中的 class2.py 调用file1.py所以我在file1.py开头所做的是

from folder2.class2 import Class2

But the following issue arises:但是会出现以下问题:

ModuleNotFoundError: No module named 'folder2'

so I tried something else:所以我尝试了别的东西:

from .folder2.class2 import Class2

the following issue arises:出现以下问题:

ImportError: attempted relative import with no known parent package

I read a solution on the site where you add __init.py__ in the folder2 but it didn't help.我在您在folder2中添加__init.py__的站点上阅读了一个解决方案,但它没有帮助。

Any suggestions please?有什么建议吗? Thank you.谢谢。

You can insert any path into your sys via the sys.path.insert method:您可以通过sys.path.insert方法将任何路径插入到您的 sys 中:

import sys
path = '\\'.join(__file__.split("\\")[:-2])
sys.path.insert(1, path)

from folder2.class2 import Class2

In the above code I made it so that the directory holding folders folder1 and folder2 gets inserted into the system.在上面的代码中,我将包含文件夹folder1folder2的目录插入到系统中。 If the location of the directories is fixed, a more clear way would be to directly use the path of the folder:如果目录的位置是固定的,更清晰的方法是直接使用文件夹的路径:

path = 'C:\\Users\\User\\Desktop'
sys.path.insert(1, path)

folder1:文件夹1:
-- __init__.py -- __init__.py
-- file1.py -- 文件1.py
folder2:文件夹2:
-- __init__.py -- __init__.py
-- class2.py -- class2.py

in class2.py :class2.py中:

class Class2():
    def __init__(self):
        pass
    ...

in file1.py :file1.py中:

import sys
sys.append('..')
from folder2.class2 import Class2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM