无实例的方法docstring,Python

2024-04-19 07:59:08 发布

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

在Python中,如何在没有类实例的情况下访问方法上的docstring?你知道吗


Tags: 实例方法情况docstring
2条回答

您可以使用__doc__

class Test():
    def test_method(self):
        """I'm a docstring"""
        print "test method"


print Test.test_method.__doc__  # prints "I'm a docstring"

或者,getdoc()来自inspect模块:

inspect.getdoc(object)

Get the documentation string for an object, cleaned up with cleandoc().

print inspect.getdoc(Test.test_method)  # prints "I'm a docstring"

您可以在此处使用^{}

>>> class Test:
...     def foo(self, bar):
...             """ Returns the parameter passed """
...             return bar
... 
>>> help(Test.foo)

退货:

Help on method foo in module __main__:

foo(self, bar) unbound __main__.Test method
    Returns the parameter passed
(END) 

相关问题 更多 >