【问题标题】:How do you read the source code of a Python module?你如何阅读 Python 模块的源代码?
【发布时间】:2018-09-27 22:44:00
【问题描述】:

我试图了解一些内置 Python 模块是如何工作的。

例如,用代码:

from Tkinter import *
root = Tk()
root.mainloop()

函数Tk的定义在哪里?

我一直在搜索tkinter source code,但找不到。 代码多次调用import Tkinter,这也很奇怪,因为这个 Tkinter,那它为什么要自己导入呢?

希望有人能帮助解决我的困惑

【问题讨论】:

标签: python tkinter python-import python-module


【解决方案1】:

虽然 cxw 的回答准确无误,但如果您发现自己经常查看 Python 模块的代码,我建议您安装 IPython。这是一个更好的python控制台版本:

$ pip install IPython
...
$ ipython

然后,要查看类/函数/模块的代码,请输入其名称并添加??

from Tkinter import *
Tk??

【讨论】:

    【解决方案2】:

    class Tk 在:

    一般来说,当你import Foo时,如果Foo是一个使用Python代码实现的模块,并且Python的search path中有一个Foo/__init__.py,则该文件运行。 Some more information here, 加上Python 2Python 3 的模块的官方文档。对于 Python 解释器中内置的模块可能不是这种情况,例如 2.7 的 Tkinter

    Tkinter 细节

    • 在 Python 2 中,Tkinter 是 Python 模块,tkinter(小写)是 Tkinter 使用的 C 模块 (source)。
    • 在 Python 3 中,tkinter(小写)是 Python 模块,_tkinter(带下划线)是 tkinter 使用的 C 模块 (source)。

    【讨论】:

    • 在python2.7中,Tk在__init__.py中是not。它在 Tkinter.py 中。我认为它只存在于 python 3 中的 __init__.py 中。在这种情况下,我们知道 OP 使用的是 python2,因为他们使用的是 Tkinter 而不是 tkinter
    猜你喜欢
    • 2019-04-16
    • 2019-01-09
    • 2013-05-16
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    相关资源
    最近更新 更多