打印定义lambda函数的代码[重复](print the code which defined a lambda function [duplicate])

编程入门 行业动态 更新时间:2024-10-26 10:33:45
打印定义lambda函数的代码[重复](print the code which defined a lambda function [duplicate])

这个问题在这里已经有了答案:

我如何获得Python函数的源代码? 10个答案

我希望能够打印一个lambda函数的定义代码。

例如,如果我通过lambda语法定义了这个函数:

>>>myfunction = lambda x: x==2 >>>print_code(myfunction)

我想要得到这个输出:

x==2

This question already has an answer here:

How can I get the source code of a Python function? 13 answers

I'd like to be able to print the definition code of a lambda function.

Example if I define this function through the lambda syntax:

>>>myfunction = lambda x: x==2 >>>print_code(myfunction)

I'd like to get this output:

x==2

最满意答案

只要您将代码保存到源文件,您就可以使用inspect模块检索对象的源代码。

例如:打开编辑器类型:

myfunction = lambda x: x==2

保存为lamtest.py

打开shell类型的python来获得交互式python类型如下:

>>>from lamtest import myfunc >>>import inspect >>>inspect.getsource(myfunc)

结果:

'myfunc = lambda x: x==2\n'

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

save as lamtest.py

open shell type python to get to interactive python type the following:

>>>from lamtest import myfunc >>>import inspect >>>inspect.getsource(myfunc)

the result:

'myfunc = lambda x: x==2\n'

更多推荐

本文发布于:2023-08-05 23:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1441436.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   定义   代码   lambda   print

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!