如何从同级文件夹中导入Python模块? [英] How to import a Python module from a sibling folder?
本文介绍了如何从同级文件夹中导入Python模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经历了许多关于Python的相对导入问题,但我无法理解该问题/无法正常工作.
I have gone through many Python relative import questions but I can't understand the issue/get it to work.
我的目录结构是:
Driver.py
A/
Account.py
__init__.py
B/
Test.py
__init__.py
Driver.py
from B import Test
Account.py
class Account:
def __init__(self):
self.money = 0
Test.py
from ..A import Account
当我尝试运行时:
python Driver.py
我得到了错误
Traceback (most recent call last):
from B import Test
File "B/Test.py", line 1, in <module> from ..A import Account
ValueError: Attempted relative import beyond toplevel package
推荐答案
之所以发生这种情况,是因为就Python而言,A
和B
是独立的,不相关的软件包.
This is happening because A
and B
are independent, unrelated, packages as far as Python is concerned.
在与Driver.py
相同的目录中创建一个__init__.py
,所有内容均应按预期工作.
Create a __init__.py
in the same directory as Driver.py
and everything should work as expected.
这篇关于如何从同级文件夹中导入Python模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文