可能重复:
About python's built in sort() method寻找内建Python函数的源代码?
有没有办法,看看如何内置函数在python工作?我不是说只是如何使用它们,又是如何被他们建造,背后是什么的代码排序或列举等..?
可能重复:
About python's built in sort() method寻找内建Python函数的源代码?
有没有办法,看看如何内置函数在python工作?我不是说只是如何使用它们,又是如何被他们建造,背后是什么的代码排序或列举等..?
由于Python是开源的,你可以阅读source code。
要了解某个特定模块或功能在哪个文件中实现,通常可以打印__file__
属性。或者,您可以使用inspect
模块,请参阅inspect
文档中的Retrieving Source Code部分。
对于内置的类和方法,这不是很直接,因为inspect.getfile
和inspect.getsource
将返回一个类型错误,指出该对象是内置的。但是,许多内置类型可以在Objects
sub-directory of the Python source trunk中找到。例如,请参阅here以获取枚举类的实现或here以实现list
类型。
这里是一个食谱答案补充@克里斯的回答,CPython的已经转移到GitHub上和水银回购将不再更新:
git clone https://github.com/python/cpython.git
代码将签出到一个叫cpython
子目录 - >cd cpython
print()
定义...egrep --color=always -R 'print' | less -R
Python/bltinmodule.c
- >builtin_print()
享受。
你可以简单地使用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 --
我不得不挖稍微找到以下Built-in Functions
的来源,因为搜索会产生数千个结果。 (祝你好运搜索任何那些寻找到它的源)
无论如何,所有这些功能都在bltinmodule.c
功能定义入手builtin_{functionname}
内置来源:https://github.com/python/cpython/blob/master/Python/bltinmodule.c
很多未知的资源是Python Developer Guide。
在(有点)最近的GH issue中,增加了一个新章节来解决您所问的问题:CPython Source Code Layout。如果有什么变化,该资源也会得到更新。
你可以用'enumerate'举个例子吗? – Benjamin 2011-12-22 19:08:27
你可以看看内置枚举的测试方式[这里](http://hg.python.org/cpython/file/b36cb4602e21/Lib/test/test_enumerate.py)。 – Makoto 2011-12-22 19:18:47
枚举代码是[here](http://svn.python.org/view/python/trunk/Objects/enumobject.c?view=markup) – 2011-12-22 19:22:33