![](/img/trans.png)
[英]How to import global variables in python from a class module in another file?
[英]How to import a class from another file in python?
我是 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()
当单元测试运行时,对象是 None:
AttributeError: 'NoneType' 对象没有属性 'helloWorld'
这有什么问题? 你如何在python中导入一个类?
如果您使用的是 Python 3,则默认情况下导入是绝对的。 这意味着import example
将在模块搜索路径中的某处查找名为example
的绝对包。
因此,您可能需要相对 import 。 当您要导入与执行导入的模块相关的模块时,这很有用。 在这种情况下:
from ..example.ClassExample import ClassExample
我假设您的文件夹是 Python包,这意味着它们包含__init__.py
文件。 所以你的目录结构看起来像这样。
src
|-- __init__.py
|-- example
| |-- __init__.py
| |-- ClassExample.py
|-- test
| |-- __init__.py
| |-- ClassExampleTest.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.