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

5

我是新手Python程序员,浏览了各种Stack Overflow帖子。我感觉这应该可以工作,但事实并非如此。在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()

当单元测试运行时,对象为 None:

属性错误:'NoneType' 对象没有 'helloWorld' 属性

这是什么问题?如何在 Python 中导入一个类?

1
尝试使用 import example; print(example) 命令,以查看您是否成功导入了 example 模块,而不是 Python 导入路径中的其他模块。 - falsetru
我不明白hello怎么可能是None。 - John Gordon
这里展示的代码看起来很合理。确保你从正确的文件中导入。更改文件名以验证你没有从错误的文件中读取。 - RufusVS
当我按照@falsetru所说的做时,它会打印出"<module 'example' from '/Users/thomas/.pyenv/versions/3.6.1/lib/python3.6/site-packages/example/__init__.py'>"。 - slipperypete
你如何执行 ClassExampleTest.py(在哪个目录中)? - tdelaney
显示剩余5条评论
1个回答

7
如果您使用的是Python 3,则默认情况下,导入是绝对的。这意味着import example将在模块搜索路径中的某个地方寻找名为example的绝对包。
因此,您可能需要使用相对导入。当您想要导入一个与进行导入的模块相关的模块时,这非常有用。在这种情况下:
from ..example.ClassExample import ClassExample

我假设您的文件夹是Python,意味着它们包含__init__.py文件。因此,您的目录结构应如下所示。

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

我尝试了这个。我得到了:TypeError: 'module' object is not callable - slipperypete
啊,你的类是不是在名为 ClassExample.py 的文件中? - Nikolas Stevenson-Molnar
相对导入不适用于脚本(例如此单元测试脚本),只适用于包和模块。脚本不在包中,因此没有相对的对象。 - tdelaney
你的导入已经成功了,但是我不得不从.pyenv/versions/3.6.1/lib/python3.6/site-packages/example中删除示例文件夹...我不知道它最初是怎么出现的。 - slipperypete
@Dan 这很奇怪... 相对导入的重点在于,site-packages 中的任何内容都不应该被考虑。 - Nikolas Stevenson-Molnar
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接