2014-05-02 104 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

相關問題