如何从函数内部打印python函数的Docstring? [英] How to print Docstring of python function from inside the function itself?
问题描述
我想从函数内部打印一个python函数的docstring。例如
。
def my_function(self):
我的函数的文档字符串。
#在这里打印文档字符串。
目前我正在执行 my_function
已被定义。
print my_function .__ doc__
但宁愿让函数自己做这件事。
我试过调用 print self ._ doc __
打印self.my_function .__ doc __
和在my_function中打印此.__ doc __
def my_func():
print my_func .__ doc__
只要您不会更改绑定到名称 my_func
的对象。
new_func_name = my_func
my_func =无
new_func_name()
#不打印任何东西,因为my_func是None且None没有文档字符串
这是相当罕见的,但它们确实发生了。然而,如果你写这样的装饰器:
<$ p
def passin(func):
def wrapper(* args,** kwargs):
返回func(func,* args,** kwargs)
返回包装
现在您可以执行此操作了:
@passmein
def my_func(me):
打印我.__ doc__
这将确保你的函数获得对自身的引用(类似于 self
)作为它的第一个参数,所以它总是可以获得正确功能的文档字符串。如果使用方法,通常 self
成为第二个参数。
I want to print the docstring of a python function from inside the function itself. for eg.
def my_function(self):
"""Doc string for my function."""
# print the Docstring here.
At the moment I am doing this directly after my_function
has been defined.
print my_function.__doc__
But would rather let the function do this itself.
I have tried calling print self.__doc__
print self.my_function.__doc__
and print this.__doc__
inside my_function but this did not work.
def my_func():
"""Docstring goes here."""
print my_func.__doc__
This will work as long as you don't change the object bound to the 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
Situations in which you'd do this are rather rare, but they do happen.
However, if you write a decorator like this:
def passmein(func):
def wrapper(*args, **kwargs):
return func(func, *args, **kwargs)
return wrapper
Now you can do this:
@passmein
def my_func(me):
print me.__doc__
And this will ensure that your function gets a reference to itself (similar to self
) as its first argument, so it can always get the docstring of the right function. If used on a method, the usual self
becomes the second argument.
这篇关于如何从函数内部打印python函数的Docstring?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!