您如何阅读 Python 模块的源代码?
How do you read the source code of a Python module?
我正在尝试了解一些内置 Python 模块是如何在幕后工作的。
例如,使用代码:
from Tkinter import *
root = Tk()
root.mainloop()
函数的定义在哪里Tk
?
我一直在搜索 tkinter source code 但找不到。
代码多次调用 import Tkinter
这也很奇怪,因为这个 是 Tkinter
,为什么它要导入自己?
希望有人能帮我解惑
class Tk
在:
- Py 2.7:
Tkinter.py
- Py 3.6:
__init__.py
。
一般来说,当你import Foo
时,如果Foo
是使用Python代码实现的模块,并且Python中有一个Foo/__init__.py
' s search path, that file runs. Some more information here, plus official docs on modules for Python 2 or Python 3。 Python 解释器内置的模块可能不是这种情况,例如 2.7 的 Tkinter
.
Tkinter
细节
虽然 cxw 的回答准确无误,但如果您发现自己经常查看 Python 模块的代码,我建议安装 IPython。这是 python 控制台的更好版本:
$ pip install IPython
...
$ ipython
然后,要查看 class / 函数 / 模块的代码,请输入其名称并添加 ??
:
from Tkinter import *
Tk??
我正在尝试了解一些内置 Python 模块是如何在幕后工作的。
例如,使用代码:
from Tkinter import *
root = Tk()
root.mainloop()
函数的定义在哪里Tk
?
我一直在搜索 tkinter source code 但找不到。
代码多次调用 import Tkinter
这也很奇怪,因为这个 是 Tkinter
,为什么它要导入自己?
希望有人能帮我解惑
class Tk
在:
- Py 2.7:
Tkinter.py
- Py 3.6:
__init__.py
。
一般来说,当你import Foo
时,如果Foo
是使用Python代码实现的模块,并且Python中有一个Foo/__init__.py
' s search path, that file runs. Some more information here, plus official docs on modules for Python 2 or Python 3。 Python 解释器内置的模块可能不是这种情况,例如 2.7 的 Tkinter
.
Tkinter
细节
虽然 cxw 的回答准确无误,但如果您发现自己经常查看 Python 模块的代码,我建议安装 IPython。这是 python 控制台的更好版本:
$ pip install IPython
...
$ ipython
然后,要查看 class / 函数 / 模块的代码,请输入其名称并添加 ??
:
from Tkinter import *
Tk??