2014-05-02 101 views
1

我想知道是否有办法打印什么功能定义?有没有办法在Python中打印函数的定义

所以如果我想要做的事,如:

def hello(): 
    print 'hello' 

some_function_to_show_definition(hello()) 

和输出应该是:

print 'hello' 

就乱搞的蟒蛇,我只是想知道:)

+0

你可能想检查[https://github.com/ipython/ipython/blob/313df3800a05f4ef72fb7bf4509ed699926cb1b2/IPython/core/oinspect.py] – user3570335

回答

3

inspect是要走的路:

In [8]: def foo(): 
    ...:  print 'hello' 
    ...:  

In [9]: import inspect 

In [10]: inspect.getsourcelines(foo) 
Out[10]: ([u'def foo():\n', u" print 'hello'\n"], 1) 
+0

你刚刚击败了我!请注意,这在'CPython'交互模式下不起作用。 – ubomb

+0

是的,如果一个程序依赖于这种低级内省,这可能不是一个好主意。 – Grapsus

相关问题