当前位置 : 主页 > 编程语言 > python >

在Python类继承中继承docstrings

来源:互联网 收集:自由互联 发布时间:2021-06-25
我正在尝试在 Python中进行一些类继承.我希望每个班级和继承的班级都有良好的文档字符串.所以我认为对于继承的类,我希望它: 继承基类docstring 可能会将相关的额外文档附加到docstr
我正在尝试在 Python中进行一些类继承.我希望每个班级和继承的班级都有良好的文档字符串.所以我认为对于继承的类,我希望它:

>继承基类docstring
>可能会将相关的额外文档附加到docstring

在类继承情况下是否有任何(可能是优雅或pythonic)方式进行此类文档字符串操作?多重继承怎么样?

你并不是唯一的一个!不久之前有关于comp.lang.python的讨论,并且创建了一个食谱.看看 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
网友评论