我正试图从文件grocery.py
导入类Store
,但无法使用__init__.py
。
下面是我的文件结构-
主文件夹:
Grocery
__init__.py
grocery.py(which contains class Store())
tests
__init__.py
test_grocery.py
test_grocery.py
:的代码
import unittest
from ..Grocery.grocery import Store
class TestCases(unittest.TestCase):
def test_cases_getSubTotal(self):
store1 = Store()
store1.activate()
self.assertTrue(store1.is_active())
def test_cases_getDiscount(self):
store2 = Store()
store2.add_points(25)
self.assertEqual(store2.get_points(), 25)
if __name__ == '__main__':
unittest.main()
终端输出:
from ..Grocery.grocery import Store
ImportError: attempted relative import with no known parent package
您的导入必须只包含class_name.py,然后导入函数或类。导入也区分大小写。
from Grocery import Store
除非修改sys.path ,否则无法从父目录导入
Grocery
__init__.py
grocery.py(which contains class Store())
tests
__init__.py(import TestCases from test_grocery.y)
test_grocery.py
然后运行:
python -m unittest tests