是否可以在Python中将函数作为字符串打印? [英] Is it possible to print a function as a string in Python?
本文介绍了是否可以在Python中将函数作为字符串打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Python可以打印函数定义吗?
In Javascript,可以将函数的代码打印为字符串吗?
In Javascript, it is possible to print a function's code as a string?
Javascript中的示例:
Example in Javascript:
function thisFunctionPrintsItself(){
return thisFunctionPrintsItself.toString();
}
是否可以在Python中执行相同操作?
Is it possible to do the same in Python?
推荐答案
您可以这样做,但结果没有用,因为所有内容都先编译为字节码。
You can do it, but the result isn't useful since everything is compiled to bytecode first.
def printItself():
print repr(printItself.func_code.co_code)
你也可以使用 dis
模块进行反汇编,但不能保证结果的可移植性。
You can also use the dis
module for disassembly, but the results aren't garuenteed to be portable.
def disassembleItself():
print __import__('dis').dis(disassembleItself)
这篇关于是否可以在Python中将函数作为字符串打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文