提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
查看源码
方法一、ctrl + 点击函数名
在Pycharm中,按住Ctrl,用鼠标点击函数
如果点击后,跳转到的地方仅仅是一堆解释说明,这表明该函数是基于C语言实现的,那么跳转到方法三
方法二、通过模块文件路劲查看
明确函数处于哪个模块
首先需要知道该函数属于哪个模块,在IDLE中使用help函数:help(函数名)查看该函数属于哪个module
>>> help(eval)
Help on built-in function eval in module builtins:
eval(source, globals=None, locals=None, /)
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
>>>
查看模块所处的位置,查看源码
1.查看模块所处的位置有两种方法:
- 方法A:import sys和import os,然后用
sys.modules[模块名]
获取模块所处位置 - 方法B:import 模块,然后用
模块名.__file__
获取模块所处位置 - 方法c:最直接的方法. 直接print(模块名).
print(random)
例子
import random
print(random)
结果:
<module 'random' from 'D:\\python39\\lib\\random.py'>
2.打开对应的py文件,找到该内置函数就可查看源码了。
以os.makedirs()函数为例,分别用这两种方法查看模块的位置(PS 如果我们看不到模块所处位置,说明该模块是基于C语言实现,跳转到方法三)
>>> import os
>>> import sys
>>> sys.modules['os']
<module 'os' from 'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python39\\lib\\os.py'>
>>> os.__file__
'C:\\Users\\admin\\AppData\\Local\\Programs\\Python\\Python39\\lib\\os.py'
>>>
然后我们找到对应的文件,打开该文件,进行搜索,就可看到函数源码,如果搜不到,跳转到方法三
方法三、查看源码
1.如果该函数在本地计算机上找不到,说明该函数所处的模块是基于C语言实现的,进github查看
2.比如上文的eval()函数,该函数是内置函数,内置函数可在具体位置https://github.com/animalize/cpython/blob/master/Python/bltinmodule.c
内查找
3.如果觉得github网页不太适合查看,可参考https://flaggo.github.io/python3-source-code-analysis/preface/code-organization/ 1.2章节<Python 源代码的组织 >查看说明文档,将源码下载到本地
查看某个模块有哪些内容
>>>