首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python中继承方法的文档字符串

在Python中继承方法的文档字符串
EN

Stack Overflow用户
提问于 2011-11-12 05:26:08
回答 3查看 8.9K关注 0票数 57

我有一个具有文档字符串的OO层次结构,它需要与代码本身一样多的维护。例如,

代码语言:javascript
复制
class Swallow(object):
    def airspeed(self):
        """Returns the airspeed (unladen)"""
        raise NotImplementedError

class AfricanSwallow(Swallow):
    def airspeed(self):
        # whatever

现在,问题是AfricanSwallow.airspeed没有继承超类方法的文档字符串。我知道我可以使用模板方法模式保留文档字符串,即

代码语言:javascript
复制
class Swallow(object):
    def airspeed(self):
        """Returns the airspeed (unladen)"""
        return self._ask_arthur()

并在每个子类中实现_ask_arthur。然而,我想知道是否有其他方法可以继承文档字符串,也许是一些我还没有发现的装饰器?

EN

回答 3

Stack Overflow用户

发布于 2016-07-17 02:30:01

仅供大家参考:从Python3.5开始,inspect.getdoc自动从继承层次结构中检索文档字符串。

因此,上面的响应对于Python 2很有用,或者如果您想更有创意地合并父级和子级的文档字符串。

我还创建了一些lightweight tools for docstring inheritance。它们开箱即用,支持一些不错的默认文档字符串样式(numpy、google、reST)。您也可以轻松地使用自己的文档字符串样式

票数 18
EN

Stack Overflow用户

发布于 2014-05-31 06:20:23

下面的修改还处理属性和混入类。我还遇到了一种情况,我不得不使用func.__func__ (用于“实例方法”),但我不完全确定为什么其他解决方案没有解决这个问题。

代码语言:javascript
复制
def inherit_docs(cls):
    for name in dir(cls):
        func = getattr(cls, name)
        if func.__doc__: 
            continue
        for parent in cls.mro()[1:]:
            if not hasattr(parent, name):
                continue
            doc = getattr(parent, name).__doc__
            if not doc: 
                continue
            try:
                # __doc__'s of properties are read-only.
                # The work-around below wraps the property into a new property.
                if isinstance(func, property):
                    # We don't want to introduce new properties, therefore check
                    # if cls owns it or search where it's coming from.
                    # With that approach (using dir(cls) instead of var(cls))
                    # we also handle the mix-in class case.
                    wrapped = property(func.fget, func.fset, func.fdel, doc)
                    clss = filter(lambda c: name in vars(c).keys() and not getattr(c, name).__doc__, cls.mro())
                    setattr(clss[0], name, wrapped)
                else:
                    try:
                        func = func.__func__ # for instancemethod's
                    except:
                        pass
                    func.__doc__ = doc
            except: # some __doc__'s are not writable
                pass
            break
    return cls
票数 4
EN

Stack Overflow用户

发布于 2016-07-07 22:59:07

代码语言:javascript
复制
def fix_docs(cls):
    """ copies docstrings of derived attributes (methods, properties, attrs) from parent classes."""
    public_undocumented_members = {name: func for name, func in vars(cls).items()
                                   if not name.startswith('_') and not func.__doc__}

    for name, func in public_undocumented_members.iteritems():
        for parent in cls.mro()[1:]:
            parfunc = getattr(parent, name, None)
            if parfunc and getattr(parfunc, '__doc__', None):
                if isinstance(func, property):
                    # copy property, since its doc attribute is read-only
                    new_prop = property(fget=func.fget, fset=func.fset,
                                        fdel=func.fdel, doc=parfunc.__doc__)
                    cls.func = new_prop
                else:
                    func.__doc__ = parfunc.__doc__
                break
    return cls
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8100166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档