76

関数自体の内部から Python 関数のドキュメント文字列を出力したいと考えています。たとえば。

def my_function(self):
  """Doc string for my function."""
  # print the Docstring here.

現時点では、my_function定義された直後にこれを行っています。

print my_function.__doc__

しかし、関数自体にこれをさせたいと思います。

my_function 内で呼び出してみprint self.__doc__ print self.my_function.__doc__ましたが、うまくいきませんでした。print this.__doc__

4

8 に答える 8

84
def my_func():
    """Docstring goes here."""
    print my_func.__doc__

name にバインドされたオブジェクトを変更しない限り、これは機能しますmy_func

new_func_name = my_func
my_func = None

new_func_name()
# doesn't print anything because my_func is None and None has no docstring

これを行う状況はかなりまれですが、実際に発生します。

ただし、次のようなデコレータを作成すると:

def passmein(func):
    def wrapper(*args, **kwargs):
        return func(func, *args, **kwargs)
    return wrapper

今、あなたはこれを行うことができます:

@passmein
def my_func(me):
    print me.__doc__

selfこれにより、関数が最初の引数として( と同様に) それ自体への参照を取得することが保証されるため、常に正しい関数の docstring を取得できます。メソッドで使用すると、通常selfは 2 番目の引数になります。

于 2012-01-11T19:57:20.333 に答える
9

これは機能するはずです(私のテストでは機能し、出力も含まれています)。おそらく__doc__getdocの代わりに使用できますが、私はそれが好きなので、それを使用しました。また、クラス/メソッド/関数の名前を知っている必要はありません。

クラス、メソッド、関数の両方の例。それがあなたが探していたものでない場合は教えてください:)

from inspect import *

class MySelfExplaningClass:
    """This is my class document string"""

    def __init__(self):
        print getdoc(self)

    def my_selfexplaining_method(self):
        """This is my method document string"""
        print getdoc(getattr(self, getframeinfo(currentframe()).function))


explain = MySelfExplaningClass()

# Output: This is my class document string

explain.my_selfexplaining_method()

# Output: This is my method document string

def my_selfexplaining_function():
    """This is my function document string"""
    print getdoc(globals()[getframeinfo(currentframe()).function])

my_selfexplaining_function()

# Output: This is my function document string
于 2012-01-12T01:12:52.157 に答える
6

これは機能します:

def my_function():
  """Docstring for my function"""
  #print the Docstring here.
  print my_function.__doc__

my_function()

Python 2.7.1 で

これも機能します:

class MyClass(object):
    def my_function(self):
        """Docstring for my function"""
        #print the Docstring here, either way works.
        print MyClass.my_function.__doc__
        print self.my_function.__doc__


foo = MyClass()

foo.my_function()

ただし、これは単独では機能しません。

class MyClass(object):
    def my_function(self):
        """Docstring for my function"""
        #print the Docstring here.
        print my_function.__doc__


foo = MyClass()

foo.my_function()

NameError: グローバル名 'my_function' が定義されていません

于 2012-01-11T16:30:56.980 に答える
4

これを行うには、まだ誰も言及していない非常に簡単な方法があります。

import inspect

def func():
    """Doc string"""
    print inspect.getdoc(func)

そして、これはあなたが望むことをします。

ここでは派手なことは何もありません。起こっていることfunc.__doc__は、関数内で実行することにより、属性の解決が十分に延期さ__doc__れ、期待どおりに機能するようになるだけです。

コンソール スクリプトのエントリ ポイントとして docopt と共に使用します。

于 2017-01-11T13:27:55.403 に答える
2

関数ではなくクラスメソッドのように質問を投げかけました。ここでは名前空間が重要です。print my_function.__doc__my_function はグローバル名前空間にあるため、関数の場合は問題ありません。

クラスメソッドの場合は、 thenprint self.my_method.__doc__が最適です。

メソッドの名前を指定せずに変数を渡したい場合は、組み込み関数 hasattr(object,attribute) と getattr(obj,attr) を使用できます。メソッドの名前である文字列を使用して変数を渡すことができます。例えば

class MyClass:
    def fn(self):
        """A docstring"""
        print self.fn.__doc__ 

def print_docstrings(object):
   for method in dir( object ):
       if method[:2] == '__':  # A protected function
           continue
       meth = getattr( object, method )
       if hasattr( meth , '__doc__' ):
           print getattr( meth , '__doc__' )

x = MyClass()
print_docstrings( x )
于 2012-01-11T16:35:31.277 に答える
1

試す:

class MyClass():
    # ...
    def my_function(self):
        """Docstring for my function"""
        print MyClass.my_function.__doc__
        # ...

(*) 後にコロン ( :)がありませんでしたmy_function()

于 2012-01-11T16:22:51.200 に答える