2013-04-25 60 views
2

有沒有辦法來檢查一個函數或方法在python裏面的功能類似於Matlab中的幫助函數。我想獲得該功能的定義,而不必谷歌它。Python:函數文檔

回答

10

是的,你可以在python交互式解釋器中調用help(whatever)

>>> help 
Type help() for interactive help, or help(object) for help about object. 

>>> help(zip) 
Help on built-in function zip in module __builtin__: 

zip(...) 
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] 

    Return a list of tuples, where each tuple contains the i-th element 
    from each of the argument sequences. The returned list is truncated 
    in length to the length of the shortest argument sequence. 

你甚至可以通過(引用)關鍵字,並得到非常詳細的幫助:

>>> help('if') 
The ``if`` statement 
******************** 

The ``if`` statement is used for conditional execution: 

    if_stmt ::= "if" expression ":" suite 
       ("elif" expression ":" suite)* 
       ["else" ":" suite] 

It selects exactly one of the suites by evaluating the expressions one 
by one until one is found to be true (see section *Boolean operations* 
for the definition of true and false); then that suite is executed 
(and no other part of the ``if`` statement is executed or evaluated). 
If all expressions are false, the suite of the ``else`` clause, if 
present, is executed. 

Related help topics: TRUTHVALUE 

>>> help('def') 
Function definitions 
******************** 

A function definition defines a user-defined function object 
.... 

甚至一般的主題:

>>> help('FUNCTIONS') 
Functions 
********* 

Function objects are created by function definitions. The only 
operation on a function object is to call it: ``func(argument-list)``. 

There are really two flavors of function objects: built-in functions 
and user-defined functions. Both support the same operation (to call 
the function), but the implementation is different, hence the 
different object types. 

See *Function definitions* for more information. 

Related help topics: def, TYPES 

調用內置的幫助系統。 (此功能用於交互式使用。)如果未提供參數,則交互式幫助系統將在解釋器控制檯上啓動。

如果參數是一個字符串,則該字符串將被查找爲模塊,函數,類,方法,關鍵字或文檔主題的名稱,並在控制檯上打印幫助頁。

如果參數是任何其他類型的對象,則會生成該對象上的幫助頁面。

+1

+1,我從來不知道把字符串傳遞給'help()'。 – Blender 2013-04-25 22:37:16

+0

感謝您的快速和徹底的答案。字符串的東西是相當有幫助的,不知道爲什麼我沒有完全嘗試它。 同樣在玩過之後,我發現你必須輸入'help('module.method')'來獲得方法的幫助,所以對於sqrt'help('math.sqrt')'並且追加它的'help( 'list.append')' – Greatporedout 2013-04-25 23:14:27

1

help()函數爲您提供幾乎所有的幫助,但如果您搜索某個東西(如要使用的模塊),請鍵入help('modules'),它將搜索可用的模塊。

然後,如果您需要查找有關模塊的信息,請輸入dir(module_name)以查看模塊中定義的方法。

+0

令人驚訝的是,我通過了150頁的Python書,並且從未提及過dir()或help()。謝謝!! – Greatporedout 2013-04-25 23:19:18