2011-12-22 61 views

回答

71

由于Python是开源的,你可以阅读source code

要了解某个特定模块或功能在哪个文件中实现,通常可以打印__file__属性。或者,您可以使用inspect模块,请参阅inspect文档中的Retrieving Source Code部分。

对于内置的类和方法,这不是很直接,因为inspect.getfileinspect.getsource将返回一个类型错误,指出该对象是内置的。但是,许多内置类型可以在Objects sub-directory of the Python source trunk中找到。例如,请参阅here以获取枚举类的实现或here以实现list类型。

+0

你可以用'enumerate'举个例子吗? – Benjamin 2011-12-22 19:08:27

+2

你可以看看内置枚举的测试方式[这里](http://hg.python.org/cpython/file/b36cb4602e21/Lib/test/test_enumerate.py)。 – Makoto 2011-12-22 19:18:47

+3

枚举代码是[here](http://svn.python.org/view/python/trunk/Objects/enumobject.c?view=markup) – 2011-12-22 19:22:33

14

iPython外壳使这很容易:function?会给你的文件。 function??也显示了代码。但这只适用于纯Python函数。

然后你可以总是download(c)Python的源代码。

如果您对核心功能的pythonic实现感兴趣,请查看PyPy源代码。

+1

PyPy对大多数内置的东西使用RPython,它几乎可以像C一样低级,几乎和Python一样高级。通常在两者之间。在任何情况下,它都是静态类型的,所以它不是Python。 – delnan 2011-12-22 19:19:41

+0

查看查看内置函数源代码的早期项目:https://github.com/punchagan/cinspect – Thomas 2014-07-23 17:38:10

20

这里是一个食谱答案补充@克里斯的回答,CPython的已经转移到GitHub上和水银回购将不再更新:

  1. 必要时安装的Git。
  2. git clone https://github.com/python/cpython.git

  3. 代码将签出到一个叫cpython子目录 - >cd cpython

  4. 比方说,我们正在寻找print()定义...
  5. egrep --color=always -R 'print' | less -R
  6. 啊哈!请参阅Python/bltinmodule.c - >builtin_print()

享受。

4

你可以简单地使用help()命令获得关于内建函数及其代码的帮助。

为如: 如果你想看到的STR()的代码,只需键入 - help(str)

它将返回这个样子,

>>> help(str) 
Help on class str in module __builtin__: 

class str(basestring) 
| str(object='') -> string 
| 
| Return a nice string representation of the object. 
| If the argument is a string, the return value is the same object. 
| 
| Method resolution order: 
|  str 
|  basestring 
|  object 
| 
| Methods defined here: 
| 
| __add__(...) 
|  x.__add__(y) <==> x+y 
| 
| __contains__(...) 
|  x.__contains__(y) <==> y in x 
| 
| __eq__(...) 
|  x.__eq__(y) <==> x==y 
| 
| __format__(...) 
|  S.__format__(format_spec) -> string 
| 
|  Return a formatted version of S as described by format_spec. 
| 
| __ge__(...) 
|  x.__ge__(y) <==> x>=y 
| 
| __getattribute__(...) 
-- More --