作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我帮助维护一个名为 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/
我是一名优秀的程序员,十分优秀!