Python 在导入包时,不会导入该包的所有内容 - 它导入包的内容__init__.py
文件。 (或者,至少看起来是这样。)
我刚刚对此做了一些测试,发现了以下内容:
>>> import urllib
>>> dir(urllib)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
如你看到的,request
, error
, parse
, response
, and robotparser
不在那里。它只导入了__init__.py
file.
因此,为了进一步测试,我看了一下tkinter
.
Here is tkinter's folder:
因此,为了检验这个理论:__init__.py
最初是可以访问的,以下是一些与 tkinter 相关的命令:
>>> import tkinter
>>> tkinter.font
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'font'
>>> tkinter.test
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'test'
>>> tkinter.test.support
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'test'
>>> dir(tkinter)
['ACTIVE', 'ALL', 'ANCHOR', 'ARC', 'BASELINE', 'BEVEL', 'BOTH', 'BOTTOM', 'BROWSE', 'BUTT', 'BaseWidget', 'BitmapImage', 'BooleanVar', 'Button', 'CASCADE', 'CENTER', 'CHAR', 'CHECKBUTTON', 'CHORD', 'COMMAND', 'CURRENT', 'CallWrapper', 'Canvas', 'Checkbutton', 'DISABLED', 'DOTBOX', 'DoubleVar', 'E', 'END', 'EW', 'EXCEPTION', 'EXTENDED', 'Entry', 'Event', 'FALSE', 'FIRST', 'FLAT', 'Frame', 'GROOVE', 'Grid', 'HIDDEN', 'HORIZONTAL', 'INSERT', 'INSIDE', 'Image', 'IntVar', 'LAST', 'LEFT', 'Label', 'LabelFrame', 'Listbox', 'MITER', 'MOVETO', 'MULTIPLE', 'Menu', 'Menubutton', 'Message', 'Misc', 'N', 'NE', 'NO', 'NONE', 'NORMAL', 'NS', 'NSEW', 'NUMERIC', 'NW', 'NoDefaultRoot', 'OFF', 'ON', 'OUTSIDE', 'OptionMenu', 'PAGES', 'PIESLICE', 'PROJECTING', 'Pack', 'PanedWindow', 'PhotoImage', 'Place', 'RADIOBUTTON', 'RAISED', 'READABLE', 'RIDGE', 'RIGHT', 'ROUND', 'Radiobutton', 'S', 'SCROLL', 'SE', 'SEL', 'SEL_FIRST', 'SEL_LAST', 'SEPARATOR', 'SINGLE', 'SOLID', 'SUNKEN', 'SW', 'Scale', 'Scrollbar', 'Spinbox', 'StringVar', 'TOP', 'TRUE', 'Tcl', 'TclError', 'TclVersion', 'Text', 'Tk', 'TkVersion', 'Toplevel', 'UNDERLINE', 'UNITS', 'VERTICAL', 'Variable', 'W', 'WORD', 'WRITABLE', 'Widget', 'Wm', 'X', 'XView', 'Y', 'YES', 'YView', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_cnfmerge', '_default_root', '_exit', '_flatten', '_join', '_magic_re', '_setit', '_space_re', '_splitdict', '_stringify', '_support_default_root', '_test', '_tkerror', '_tkinter', '_varnum', 'constants', 'getboolean', 'getdouble', 'getint', 'image_names', 'image_types', 'mainloop', 're', 'sys', 'wantobjects']
注意到mainloop
in the dir
回复,我检查了__init__.py
- 果然,mainloop()
在那里定义。
所以,为了回答你的问题,Python只加载urllib
's __init__.py
当你这样做时归档import urllib
- not request.py
.
edit:作为另一点,在dir(tkinter)
,其中定义了一些变量tkinter.constants
, 并不是__init__.py
。那是因为在tkinter
's __init__.py
,它导入tkinter.constants
with from tkinter.constants import *
.