Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中从另一个文件导入类?_Python_Python 3.x - Fatal编程技术网

如何在python中从另一个文件导入类?

如何在python中从另一个文件导入类?,python,python-3.x,Python,Python 3.x,我是python新手,看过各种堆栈溢出帖子。我觉得这应该行得通,但不行。如何从python中的另一个文件导入类? 此文件夹结构 src/example/ClassExample src/test/ClassExampleTest 我有这门课 class ClassExample: def __init__(self): pass def helloWorld(self): return "Hello World!" 我有这

我是python新手,看过各种堆栈溢出帖子。我觉得这应该行得通,但不行。如何从python中的另一个文件导入类? 此文件夹结构

src/example/ClassExample
src/test/ClassExampleTest
我有这门课

class ClassExample:
    def __init__(self):
        pass

    def helloWorld(self):
        return "Hello World!"
我有这个考试班

import unittest
from example import ClassExample

class ClassExampleTest(unittest.TestCase):

    def test_HelloWorld(self):
        hello = ClassExample()
        self.assertEqual("Hello World!", hello.helloWorld())

if __name__ == '__main__':
    unittest.main()
当单元测试运行时,对象为无:

AttributeError:“非类型”对象没有属性“helloWorld”


这个怎么了?如何在python中导入类?

如果您使用的是python 3,那么默认情况下导入是绝对的。这意味着
import-example
将在中的某个位置查找名为
example
的绝对包

所以,你可能想要一个新的。当您要导入与执行导入操作的模块相关的模块时,这非常有用。在这种情况下:

from ..example.ClassExample import ClassExample
我假设您的文件夹是Python,这意味着它们包含
\uuuu init\uuuu.py
文件。您的目录结构如下所示

src
|-- __init__.py
|-- example
|   |-- __init__.py
|   |-- ClassExample.py
|-- test
|   |-- __init__.py
|   |-- ClassExampleTest.py

尝试
导入示例;打印(示例)
以查看实际导入了
example
模块,而不是python导入路径中的其他模块。我不知道
hello
是如何为无的。此处显示的代码看起来合理。确保从正确的文件导入。更改文件名以验证您没有从错误的文件中读取。当我执行@falsetru所说的打印“”时,听起来站点包示例模块实际上有一个“ClassExample”类。可能性有多大?我试过了。我得到:
TypeError:“module”对象不可调用
Ah。您的类是否位于名为
ClassExample.py
的文件中?相对导入不适用于脚本(如此单元测试脚本),仅适用于包和模块。脚本不在包中,因此没有相关内容。是。就这样Nikolas@Dan,在这种情况下,您需要从.example.ClassExample导入ClassExample