2013-04-25 80 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