Python包与子包导入机制:为何自定义包无法像NumPy那样调用?
Python包与子包导入机制问题
我一直试图搞懂Python里包和子包的导入逻辑。包是包含Python模块和__init__.py文件的目录,__init__.py里可以用__all__列表定义import *时要导入的对象,子包就是带__init__.py的子目录。
我的项目结构如下:
Project/ ├── main.py └── my_pckg/ ├── __init__.py ├── functions.py └── abc/ ├── __init__.py └── A.py
我知道调用functions模块里的func_1()可以这样写:
import my_pckg.functions as pckg_fun pckg_fun.func_1() from my_pckg.functions import func_1 func_1()
调用abc子包中A模块的func_A()可以这样:
import my_pckg.abc.A as pckg_A pckg_A.func_A() from my_pckg.abc.A import func_A func_A()
但像NumPy这类库,我能直接这么调用random子包的randn():
import numpy as np np.random.randn(2)
可我用下面的代码就报错:
import my_pckg as mp mp.functions.func_1()
或者
import my_pckg as mp mp.abc.A.func_A()
错误信息分别是:
>>> mp.functions.func_1() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'my_pckg' has no attribute 'functions'
以及:
>>> mp.abc.A.func_A() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'my_pckg' has no attribute 'abc'
我猜要么创建包还有没掌握的细节,要么是我没搞明白NumPy这类库的实现逻辑。
最后,Mitch Hedberg的这个笑话完美说出了我的感受:
他们说雪碧的配方是柠檬加酸橙,但我在家试着做的时候,才发现远不止这么简单。[...]
内容的提问来源于stack exchange,提问作者S0898
相关产品推荐
相关产品推荐

