这可能是一个更一般的问题,因为我已经看到了其他模块的类似行为。但我会在模块中展示这个问题
matplotlib
. 我以为
dir(module)
列出指定模块的所有属性。所以我可以这样做:
import matplotlib
dir(matplotlib)
列出的结果中有“dateutil”,但“dates”未列出
dir(matplotlib)
. 但是我这样做:
import matplotlib.dates ## why does this work? `dir(matplotlib)` did not list it
dir(matplotlib) ## this now lists both 'dates' and 'dateutil'
为什么
目录(matplotlib)
现在把“日期”列为它的属性之一?
怎么回事?
我刚刚注意到,在我看来,dateutil实际上不是matplotlib的一部分,而是由matplotlib导入的:
In [11]: matplotlib.dateutil.__file__
Out[11]: '/anaconda3/lib/python3.6/site-packages/dateutil/__init__.py'
In [12]: matplotlib.__file__
Out[12]: '/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py'
In [13]: matplotlib.dates.__file__
Out[13]: '/anaconda3/lib/python3.6/site-packages/matplotlib/dates.py'
注意上面的输出,
matplotlib.dateutil.__file__
显示甚至不在matplotlib目录中的文件。而且我可以在文件中看到
'/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py'
DateUtil是由
matplotlib/__init__.py
.
所以当我跑的时候
目录(模块)
有没有一种简单的方法来区分哪些属性是模块本身的一部分,哪些是模块导入的?我怎么知道(除了阅读文档或matplotlib目录中的“ls”)dates也是matplotlib中的有效“属性”和“模块”?