在 Python 中继承方法的文档字符串 [英] Inheriting methods' docstrings in Python

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

问题描述

我有一个 OO 层次结构,其中包含与代码本身一样多的维护的文档字符串.例如,

I have an OO hierarchy with docstrings that take as much maintenance as the code itself. E.g.,

class Swallow(object):
    def airspeed(self):
        """Returns the airspeed (unladen)"""
        raise NotImplementedError

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

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

Now, the problem is that AfricanSwallow.airspeed does not inherit the superclass method's docstring. I know I can keep the docstring using the template method pattern, i.e.

class Swallow(object):
    def airspeed(self):
        """Returns the airspeed (unladen)"""
        return self._ask_arthur()

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

and implementing _ask_arthur in each subclass. However, I was wondering whether there's another way to have docstrings be inherited, perhaps some decorator that I hadn't discovered yet?

推荐答案

以类装饰器风格编写一个函数来为您进行复制.在Python2.5中,创建类后可以直接应用.在以后的版本中,您可以使用 @decorator 符号进行申请.

Write a function in a class-decorator style to do the copying for you. In Python2.5, you can apply it directly after the class is created. In later versions, you can apply with the @decorator notation.

这是如何做到这一点的第一次剪辑:

Here's a first cut at how to do it:

import types

def fix_docs(cls):
    for name, func in vars(cls).items():
        if isinstance(func, types.FunctionType) and not func.__doc__:
            print func, 'needs doc'
            for parent in cls.__bases__:
                parfunc = getattr(parent, name, None)
                if parfunc and getattr(parfunc, '__doc__', None):
                    func.__doc__ = parfunc.__doc__
                    break
    return cls


class Animal(object):
    def walk(self):
        'Walk like a duck'

class Dog(Animal):
    def walk(self):
        pass

Dog = fix_docs(Dog)
print Dog.walk.__doc__

在较新的 Python 版本中,最后一部分更加简单和美观:

In newer Python versions, the last part is even more simple and beautiful:

@fix_docs
class Dog(Animal):
    def walk(self):
        pass

这是一种 Pythonic 技术,与标准库中现有工具的设计完全匹配.例如,functools.total_ordering 类装饰器向类添加缺少的丰富的比较方法.再举一个例子,functools.wraps 装饰器将元数据从一个函数复制到另一个函数.

This is a Pythonic technique that exactly matches the design of existing tools in the standard library. For example, the functools.total_ordering class decorator add missing rich comparison methods to classes. And for another example, the functools.wraps decorator copies metadata from one function to another.

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

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