来自兄弟文件夹的Python导入模块 [英] Python import module from sibling folder

查看:114
本文介绍了来自兄弟文件夹的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

Driver.py

from B import Test

=== ======

=========

Account.py

Account.py

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

= ===================

====================

Test.py

from ..A import Account

==== ==============

==================

当我尝试运行时


python Driver.py

python Driver.py

我收到错误

Traceback(最近一次调用l ast):

Traceback (most recent call last):

来自B导入测试

文件B / Test.py,第1行,in来自..A导入帐户的< module>

File "B/Test.py", line 1, in <module> from ..A import Account

ValueError:尝试相对导入超出toplevel包

ValueError: Attempted relative import beyond toplevel package


推荐答案

这是因为 A 和<$就Python而言,c $ c> B 是独立的,无关的软件包。

This is happening because A and B are independent, unrelated, packages as far as Python is concerned.

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

Create a __init__.py in the same directory as Driver.py and everything should work as expected.

这篇关于来自兄弟文件夹的Python导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆