如何从同级文件夹导入 Python 模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14886143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:45:32  来源:igfitidea点击:

How to import a Python module from a sibling folder?

pythonimportmodulerelative-path

提问by Joshua

I have gone through many Python relative import questions but I can't understand the issue/get it to work.

我已经解决了许多 Python 相关的导入问题,但我无法理解这个问题/让它起作用。

My directory structure is:

我的目录结构是:

Driver.py

A/
      Account.py
      __init__.py

B/
      Test.py
      __init__.py

Driver.py

Driver.py

from B import Test

Account.py

Account.py

class Account:
def __init__(self):
    self.money = 0

Test.py

Test.py

from ..A import Account

When I try to run:

当我尝试运行时:

python Driver.py

I get the error

我收到错误

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

采纳答案by David Wolever

This is happening because Aand Bare independent, unrelated, packages as far as Python is concerned.

发生这种情况是因为就 Python 而言AB它们是独立的、不相关的包。

Create a __init__.pyin the same directory as Driver.pyand everything should work as expected.

__init__.py在同一个目录中创建一个,Driver.py一切都应该按预期工作。