Python 可以打印函数定义吗? [英] Can Python print a function definition?
问题描述
在 JavaScript 中,可以打印出函数的定义.有没有办法在 Python 中实现这一点?
(只是在交互模式下玩,我想在没有 open() 的情况下阅读模块.我只是好奇).
如果要导入函数,可以使用 inspect.getsource
:
这将在交互式提示中起作用,但显然仅适用于导入的对象(而不是在交互式提示中定义的对象).当然,它只有在 Python 可以找到源代码的情况下才能工作(因此不能在内置对象、C 库、.pyc 文件等中找到)
In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python?
(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious).
If you are importing the function, you can use inspect.getsource
:
>>> import re
>>> import inspect
>>> print inspect.getsource(re.compile)
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
return _compile(pattern, flags)
This will work in the interactive prompt, but apparently only on objects that are imported (not objects defined within the interactive prompt). And of course it will only work if Python can find the source code (so not on built-in objects, C libs, .pyc files, etc)
这篇关于Python 可以打印函数定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!