您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

以类装饰器风格编写一个函数来为您执行复制。在Python2.5中,您可以在创建类后直接应用它。在更高版本中,您可以使用@decorator表示法。

这是如何做到的第一步:

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版本中,最后一部分更加简单美观:

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

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

python 2022/1/1 18:37:28 有244人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶