如何从函数内部打印python函数的Docstring?

2024-04-18 07:45:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从函数内部打印python函数的docstring。 例如

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

目前,我是在定义了my_function之后直接这样做的。

print my_function.__doc__

但宁愿让这个函数自己来做。

我试过在函数中调用print self.__doc__print self.my_function.__doc__print this.__doc__,但这不起作用。


Tags: the函数selfforstringdochere定义
3条回答
def my_func():
    """Docstring goes here."""
    print my_func.__doc__

只要不更改绑定到名称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将成为第二个参数。

这应该有效(在我的测试中,它也包括输出)。你也许可以用__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

这是有效的:

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

my_function()

在Python2.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()

名称错误:未定义全局名称“my_function”

相关问题 更多 >