这是我使用python 3.5的应用程序结构
app
__init__.py # running the code from here
module
__init__.py
test.py # want access to this
^-- test_function() is here
test2.py # and this one too
我完全知道我可以通过以下方式访问测试。 注意我运行此操作时使用以下cmd python 3 /app/__init__.py
需要访问/app/module/test.py
from module import test
test.test_function()
# works
我也可以将它导入全球范围(不良做法)
from module.test import test_function
# works
而且我知道我也可以使用
import module.test
# works
但我想要做的是导入完整的模块(或对我的术语抱歉)
我想导入整个软件包,例如:
import module
module.test.test_function()
但我似乎得到了
AttributeError: module 'module' has no attribute 'test'
奖金问题
如果导入完整包不是一个好习惯,那么我不介意明确并使用from module import test
,请告诉我。
PS我尝试在/app/module/__init__.py中添加导入,因为它在导入期间被调用,但它似乎无法正常工作
我在import test
中添加了/app/module/__init__.py
但是当我尝试时,测试似乎是空的。
import module # module now has import test in its __init__
print(dir(module.test))
# ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
你可以看到它缺少test_function()
答案 0 :(得分:1)
Loading all modules in a folder in Python
的其他几点想法$ tree
.
├── mod
│ ├── __init__.py
│ ├── test.py
└── run.py
<强> __初始化__。PY 强>
# to import all objects use star '*' instead of name literals
from mod.test import hello_world
<强> test.py 强>
def hello_world():
print('Hello World!')
<强> run.py 强>
import mod
if __name__ == '__main__':
mod.hello_world()
结果
$ python run.py
Hello World!
您可以导入任何模块,子模块或其他任何内容,使其成为包的“公共”界面的一部分。
UPD:我强烈建议您阅读文档中的packages主题。因为它很难过
重要的是要记住所有包都是模块,但并非所有模块都是包。换句话说,包只是一种特殊的模块。具体而言,任何包含
__path__
属性的模块都被视为包。
您可以这样想:当您导入模块时,您正在加载module_name.py
文件中的所有对象,但是当您导入包时,您正在加载__init__.py
文件。
软件包通常包含所谓的公共接口,它只包含与此软件包相关的可重用组件而没有辅助函数等。这样,软件包在导入时会隐藏来自外部作用域(将在其中使用)的一些代码。