python - 为什么有时我可以使用嵌套模块中的函数而无需导入整个路径?

标签 python import module package python-import

我想知道这两种情况有什么区别?模块的内部结构是否有所不同?

那么为什么这个有效:

>>> import numpy
>>> numpy.random.RandomState
<class 'numpy.random.mtrand.RandomState'>

但是这个在我也导入嵌套模块之前不起作用:

>>> import tkinter
>>> tkinter.ttk.Spinbox
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'ttk'
>>> import tkinter.ttk
>>> tkinter.ttk.Spinbox
<class 'tkinter.ttk.Spinbox'>

我认为这一定与每个模块中的 __init__.py 文件有关,但具体的实现示例会很有帮助。

最佳答案

这种导入行为可以通过导入各个__init__.py文件中的深层类来实现。以下是项目结构的快速演示,其工作方式与真正的 numpy 和 tkinter 包几乎完全相同:

.
├── main.py
├── numpy
│   ├── __init__.py
│   └── random
│       ├── __init__.py
│       └── mtrand.py
└── tkinter
    ├── __init__.py
    └── ttk.py

numpy/__init__.py:

from .random import RandomState

numpy/random/__init__.py:

from .mtrand import RandomState

numpy/random/mtrand.py:

class RandomState:
    pass

tkinter/__init__.py:

tkinter/ttk.py:

class Spinbox:
    pass

main.py:

import numpy
import tkinter

print(numpy.random.RandomState)

try:
    print(tkinter.ttk.Spinbox)
except AttributeError as e:
    print("Error:", e)
    import tkinter.ttk
    print(tkinter.ttk.Spinbox)

Output:

<class 'numpy.random.mtrand.RandomState'>
Error: module 'tkinter' has no attribute 'ttk'
<class 'tkinter.ttk.Spinbox'>

关于python - 为什么有时我可以使用嵌套模块中的函数而无需导入整个路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60303795/

相关文章:

python - 使用 python 从 Windows 商店访问特定证书

python - PyQt : Editable QFileSystemModel in a QTreeView

eclipse - 您可以配置 eclipse 来编码协助某些导入而不是其他导入吗

python - 仅替换屏蔽的 numpy 数组中的未屏蔽值

string - Wolfram Mathematica 从多个文件导入数据

import - builtins.ImportError : cannot import name 'Empty'

module - NGINX Header 和 Body 过滤器模块

javascript - 为 AMD、CommonJS 等打包 js 库

python - 通过在 python 中使用 argparse 从我的模块传递其命令行参数来调用另一个模块

python - 鹡鸰文件 : Large file size (>2GB) upload fails