在 Python 类继承中继承文档字符串 [英] Inherit docstrings in Python class inheritance

查看:29
本文介绍了在 Python 类继承中继承文档字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Python 中进行一些类继承.我希望每个类和继承的类都有很好的文档字符串.所以我认为对于继承的类,我希望它:

I'm trying to do some class inheritance in Python. I'd like each class and inherited class to have good docstrings. So I think for the inherited class, I'd like it to:

  • 继承基类文档字符串
  • 可能会在文档字符串中附加相关的额外文档

在类继承的情况下,是否有任何(可能是优雅的或 Pythonic 的)方法来进行这种文档字符串操作?多重继承怎么样?

Is there any (possibly elegant or pythonic) way of doing this sort of docstring manipulation in a class inheritance situation? How about for multiple inheritance?

推荐答案

您不是唯一一个!不久前在 comp.lang.python 上有一个关于这个的讨论,并创建了一个配方.在此处查看.

You're not the only one! There was a discussion on comp.lang.python about this a while ago, and a recipe was created. Check it out here.

"""
doc_inherit decorator

Usage:

class Foo(object):
    def foo(self):
        "Frobber"
        pass

class Bar(Foo):
    @doc_inherit
    def foo(self):
        pass 

Now, Bar.foo.__doc__ == Bar().foo.__doc__ == Foo.foo.__doc__ == "Frobber"
"""

from functools import wraps

class DocInherit(object):
    """
    Docstring inheriting method descriptor

    The class itself is also used as a decorator
    """

    def __init__(self, mthd):
        self.mthd = mthd
        self.name = mthd.__name__

    def __get__(self, obj, cls):
        if obj:
            return self.get_with_inst(obj, cls)
        else:
            return self.get_no_inst(cls)

    def get_with_inst(self, obj, cls):

        overridden = getattr(super(cls, obj), self.name, None)

        @wraps(self.mthd, assigned=('__name__','__module__'))
        def f(*args, **kwargs):
            return self.mthd(obj, *args, **kwargs)

        return self.use_parent_doc(f, overridden)

    def get_no_inst(self, cls):

        for parent in cls.__mro__[1:]:
            overridden = getattr(parent, self.name, None)
            if overridden: break

        @wraps(self.mthd, assigned=('__name__','__module__'))
        def f(*args, **kwargs):
            return self.mthd(*args, **kwargs)

        return self.use_parent_doc(f, overridden)

    def use_parent_doc(self, func, source):
        if source is None:
            raise NameError, ("Can't find '%s' in parents"%self.name)
        func.__doc__ = source.__doc__
        return func

doc_inherit = DocInherit 

这篇关于在 Python 类继承中继承文档字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆