gpt4 book ai didi

python - 显式设置方法的文档字符串

转载 作者:太空狗 更新时间:2023-10-29 20:39:06 24 4
gpt4 key购买 nike

我帮助维护一个名为 nxt-python 的 python 包。它使用元类来定义控制对象的方法。下面是定义可用函数的方法:

class _Meta(type):
'Metaclass which adds one method for each telegram opcode'

def __init__(cls, name, bases, dict):
super(_Meta, cls).__init__(name, bases, dict)
for opcode in OPCODES:
poll_func, parse_func = OPCODES[opcode]
m = _make_poller(opcode, poll_func, parse_func)
setattr(cls, poll_func.__name__, m)

我希望能够为它添加的每个方法添加不同的文档字符串。 m 是_make_poller() 返回的方法。有任何想法吗?有什么方法可以解决 python 对更改文档字符串的限制吗?

最佳答案

对于普通函数:

def f():  # for demonstration
pass

f.__doc__ = "Docstring!"
help(f)

这适用于 python2 和 python3,适用于定义和不定义文档字符串的函数。您也可以执行 +=。请注意,它是 __doc__ 而不是 __docs__

对于方法,需要使用方法的__func__属性:

class MyClass(object):

def myMethod(self):
pass

MyClass.myMethod.__func__.__doc__ = "A really cool method"

关于python - 显式设置方法的文档字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5931386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com