Python 可以打印函数定义吗? [英] Can Python print a function definition?

查看:50
本文介绍了Python 可以打印函数定义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中,可以打印出函数的定义.有没有办法在 Python 中实现这一点?

(只是在交互模式下玩,我想在没有 open() 的情况下阅读模块.我只是好奇).

解决方案

如果要导入函数,可以使用 inspect.getsource:

<预><代码>>>>进口重新>>>进口检验>>>打印inspect.getsource(re.compile)定义编译(模式,标志= 0):编译一个正则表达式模式,返回一个模式对象."返回_compile(模式,标志)

在交互式提示中起作用,但显然仅适用于导入的对象(而不是在交互式提示中定义的对象).当然,它只有在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆