打印定义 lambda 函数的代码 [英] print the code which defined a lambda function
本文介绍了打印定义 lambda 函数的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够打印 lambda 函数的定义代码.
I'd like to be able to print the definition code of a lambda function.
例如,如果我通过 lambda 语法定义此函数:
Example if I define this function through the lambda syntax:
>>>myfunction = lambda x: x==2
>>>print_code(myfunction)
我想得到这个输出:
x==2
推荐答案
只要将代码保存到源文件就可以检索使用检查模块的对象.
As long as you save your code to a source file you can retrieve the source code of an object using the inspect module.
示例:打开编辑器类型:
example: open editor type:
myfunction = lambda x: x==2
另存为 lamtest.py
save as lamtest.py
打开shell类型python进入交互式python输入以下内容:
open shell type python to get to interactive python type the following:
>>>from lamtest import myfunc
>>>import inspect
>>>inspect.getsource(myfunc)
结果:
'myfunc = lambda x: x==2\n'
这篇关于打印定义 lambda 函数的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文