📜  Python中的帮助函数

📅  最后修改于: 2022-05-13 01:55:03.209000             🧑  作者: Mango

Python中的帮助函数

Python帮助函数用于显示模块、函数、类、关键字等的文档。

帮助函数具有以下语法:

help([object])

Python help()函数参数

object: Call help of the given object.

如果传递帮助函数时不带参数,则交互式帮助实用程序会在控制台上启动。

Python help() 示例

让我们在Python控制台中查看打印函数的文档。

Python3
help(print)


Python3
class Helper:
    def __init__(self):
        '''The helper class is initialized'''
 
    def print_help(self):
        '''Returns the help description'''
        print('helper description')
 
 
help(Helper)
help(Helper.print_help)


Python3
def my_function():
    '''Demonstrates triple double quotes
    docstrings and does nothing really.'''
 
    return None
 
print("Using __doc__:")
print(my_function.__doc__)
 
print("Using help:")
help(my_function)


输出:

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

也可以为用户定义的函数和类定义帮助函数输出。 docstring(documentation 字符串) 用于文档。它嵌套在三引号内,是类、函数或模块中的第一条语句。

让我们定义一个带有函数的类:

Python3

class Helper:
    def __init__(self):
        '''The helper class is initialized'''
 
    def print_help(self):
        '''Returns the help description'''
        print('helper description')
 
 
help(Helper)
help(Helper.print_help)

运行上述程序,我们得到第一个帮助函数的输出,如下所示:

Help on class Helper in module __main__:

class Helper(builtins.object)
 |  Methods defined here:
 |  
 |  __init__(self)
 |      The helper class is initialized
 |  
 |  print_help(self)
 |      Returns the help description
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Help on function print_help in module __main__:

print_help(self)
    Returns the help description

Python help()函数文档字符串

文档字符串在类、方法或函数声明的下方使用“'三单引号”'或“”“三双引号”””声明。所有函数都应该有一个文档字符串。

访问文档字符串:可以使用对象的 __doc__ 方法或使用帮助函数来访问文档字符串。

Python3

def my_function():
    '''Demonstrates triple double quotes
    docstrings and does nothing really.'''
 
    return None
 
print("Using __doc__:")
print(my_function.__doc__)
 
print("Using help:")
help(my_function)

输出:

Using __doc__:
Demonstrates triple double quotes
    docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:

my_function()
    Demonstrates triple double quotes
    docstrings and does nothing really.