2009-08-13 14 views

Odpowiedz

7

Wszelkie docstring jest dostępny za pośrednictwem właściwości .__doc__:

>>> print str.__doc__ 

W Pythonie 3, musisz nawias do druku:

>>> print(str.__doc__) 
3

Można wykorzystać dir( {wstawić nazwę klasy tutaj} ) aby uzyskać zawartość klasy, a następnie iterować ją, szukając metod lub innych rzeczy. Ten przykład wygląda w klasie Task metod począwszy od nazwy cmd i dostaje ich docstring:

command_help = dict() 

for key in dir(Task): 
    if key.startswith('cmd'): 
     command_help[ key ] = getattr(Task, key).__doc__ 
1

.__doc__ jest najlepszym wyborem. Możesz jednak użyć inspect.getdoc, aby uzyskać docstring. Jedną z zalet użycia tego jest to, że usuwa wcięcia z docstrukcji, które są wcięte do wyrównania z blokami kodu.

przykład:

In [21]: def foo(): 
    ....:  """ 
    ....:  This is the most useful docstring. 
    ....:  """ 
    ....:  pass 
    ....: 

In [22]: from inspect import getdoc 

In [23]: print(getdoc(foo)) 
This is the most useful docstring. 

In [24]: print(getdoc(str)) 
str(object='') -> string 

Return a nice string representation of the object. 
If the argument is a string, the return value is the same object.