可能重复:
Can Python print a function definition?是否可以在Python中将函数作为字符串打印?
在Javascript中,可以打印功能的代码作为字符串?
例在Javascript:
function thisFunctionPrintsItself(){
return thisFunctionPrintsItself.toString();
}
是否有可能做同样在Python?
可能重复:
Can Python print a function definition?是否可以在Python中将函数作为字符串打印?
在Javascript中,可以打印功能的代码作为字符串?
例在Javascript:
function thisFunctionPrintsItself(){
return thisFunctionPrintsItself.toString();
}
是否有可能做同样在Python?
您可以这样做,但结果并不实用,因为所有内容都先编译为字节码。
def printItself():
print repr(printItself.func_code.co_code)
您还可以使用dis
模块进行拆卸,但结果并不garuenteed可移植。
def disassembleItself():
print __import__('dis').dis(disassembleItself)
这就是我得到的第一个函数输出:'t \ x00 \ x00t \ x01 \ x00j \ x02 \ x00j \ x03 \ x00 \ x83 \ x01 \ x00GHd \ x00 \ x00S' – 2012-08-12 20:48:25
@Anderson - 字节码。 – Antimony 2012-08-12 20:49:13
是否有可能实际打印函数的源代码,如在Javascript中? – 2012-08-12 20:49:47
def foo():
import inspect
return inspect.getsource(foo)
print (foo())
这里,检查模块读取源文件,这样就不会工作,如果他们错过(和正在使用的只是.pyc
或.pyo
模块)或函数编译导通在交互式翻译或其他方面。
是否可以编写一个可以将另一个函数作为参数的函数,然后打印该函数的源代码? – 2012-08-12 21:47:33
这正是'inspect.getsource'所做的。 – tjollans 2012-08-12 21:49:19
你试过了吗? – 2012-08-12 20:41:22
@olly_uk我已经在Javascript中尝试过它,但不是在Python中。 – 2012-08-12 20:45:39