我对 python 很陌生,并且看过各种堆栈溢出帖子。我觉得这应该有效,但事实并非如此。如何从 python 中的另一个文件导入类?这个文件夹结构
src/example/ClassExample
src/test/ClassExampleTest
Run Code Online (Sandbox Code Playgroud)
我有这门课
class ClassExample:
def __init__(self):
pass
def helloWorld(self):
return "Hello World!"
Run Code Online (Sandbox Code Playgroud)
我有这个测试课
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()
Run Code Online (Sandbox Code Playgroud)
当单元测试运行时,对象为 None:
AttributeError:“NoneType”对象没有属性“helloWorld”
这有什么问题吗?如何在Python中导入类?
如果您使用的是 Python 3,则默认导入是绝对导入。这意味着将在模块搜索路径中的某处import example查找名为 的绝对包。example
因此,您可能需要相对导入。当您想要导入与执行导入的模块相关的模块时,这非常有用。在这种情况下:
from ..example.ClassExample import ClassExample
Run Code Online (Sandbox Code Playgroud)
我假设您的文件夹是 Python包,这意味着它们包含__init__.py文件。所以你的目录结构看起来像这样。
src
|-- __init__.py
|-- example
| |-- __init__.py
| |-- ClassExample.py
|-- test
| |-- __init__.py
| |-- ClassExampleTest.py
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16309 次 |
| 最近记录: |