1. 程式人生 > >Python獲取幫助的3種方式

Python獲取幫助的3種方式

我們可以很容易的通過Python直譯器獲取幫助。如果想知道一個物件(object)更多的資訊,那麼可以呼叫help(object)!另外還有一些有用的方法,dir(object)會顯示該物件的大部分相關屬性名,還有object._ doc _會顯示其相對應的文件字串。下面對其進行逐一介紹。

1、 help()

help函式是Python的一個內建函式。
函式原型:help([object])。
可以幫助我們瞭解該物件的更多資訊。
If no argument is given, the interactive help system starts on the interpreter console.

>>> help()

Welcome to Python 2.7!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and
using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as
"spam", type "modules spam". help> int # 由於篇幅問題,此處只顯示部分內容,下同 Help on class int in module __builtin__: class int(object) | int(x=0) -> int or long | int(x, base=10) -> int or long | ..... help>

If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

>>> help(abs)  # 檢視abs函式
Help on built-in function abs in module __builtin__:

abs(...)
    abs(number) -> number

    Return the absolute value of the argument.

>>> help(math) # 檢視math模組,此處只顯示部分內容
Help on built-in module math:

NAME
    math

FILE
    (built-in)

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)

        Return the arc cosine (measured in radians) of x.

.....

>>> 

2、dir()

dir函式是Python的一個內建函式。
函式原型:dir([object])
可以幫助我們獲取該物件的大部分相關屬性。
Without arguments, return the list of names in the current local scope.

>>> dir()  # 沒有引數
['__builtins__', '__doc__', '__name__', '__package__']
>>> 
>>> import math  # 引入一個包和一個變數,再次dir()
>>> a=3
>>> 
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'math']
>>> 

With an argument, attempt to return a list of valid attributes for that object.

>>> import math
>>> dir(math)  # math模組作為引數
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>> 

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
• If the object is a module object, the list contains the names of the module’s attributes.

>>> import math
>>> dir(math)  # math模組作為引數
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>> 

• If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

>>> dir(float)  # 型別
['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']
>>> dir(3.4)
['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']
>>> 
>>> class A:
    x=3
    y=4


>>> class B(A):
    z=5


>>> dir(B)  # 類
['__doc__', '__module__', 'x', 'y', 'z']
>>> 

• Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

3、_ doc_

在Python中有一個奇妙的特性,文件字串,又稱為DocStrings。
用它可以為我們的模組、類、函式等新增說明性的文字,使程式易讀易懂,更重要的是可以通過Python自帶的標準方法將這些描述性文字資訊輸出。
上面提到的自帶的標準方法就是_ doc _。前後各兩個下劃線。
:當不是函式、方法、模組等呼叫doc時,而是具體物件呼叫時,會顯示此物件從屬的型別的建構函式的文件字串。

>>> import math
>>> math.__doc__   # 模組
'This module is always available.  It provides access to the\nmathematical functions defined by the C standard.'
>>> abs.__doc__   # 內建函式
'abs(number) -> number\n\nReturn the absolute value of the argument.'
>>> def addxy(x,y):
    '''the sum of x and y'''
    return x+y

>>> addxy.__doc__  # 自定義函式
'the sum of x and y'
>>> a=[1,2,4]
>>> a.count.__doc__  # 方法
'L.count(value) -> integer -- return number of occurrences of value'
>>> b=3
>>> b.__doc__   # 具體的物件
"int(x=0) -> int or long\nint(x, base=10) -> int or long\n\nConvert a number or string to an integer, or return 0 if no arguments\nare given.  If x is floating point, the conversion truncates towards zero.\nIf x is outside the integer range, the function returns a long instead.\n\nIf x is not a number or if base is given, then x must be a string or\nUnicode object representing an integer literal in the given base.  The\nliteral can be preceded by '+' or '-' and be surrounded by whitespace.\nThe base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to\ninterpret the base from the string as an integer literal.\n>>> int('0b100', base=0)\n4"
>>> 

其實我們可以通過一定的手段來檢視這些文件字串,比如使用Pycharm,在對應的模組、函式、方法等上滑鼠“右擊”->Go to->Declaration。例如:檢視內建函式abs的文件字串
這裡寫圖片描述
我們再舉一個具體的物件的例子,例如,上面具體的整型物件b的doc顯示的就是其所從屬的int型別的文件字串:
這裡寫圖片描述

參考文獻:
1、Python幫助文件