我希望能够打印 lambda 函数的定义代码。
如果我通过 lambda 语法定义此函数的示例:
>>>myfunction = lambda x: x==2
>>>print_code(myfunction)
我想得到这个输出:
x==2
最佳答案
只要你把你的代码保存到一个源文件中你就可以检索到源代码 使用检查模块的对象。
示例: 打开编辑器类型:
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'
关于python - 打印定义 lambda 函数的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/334851/