为什么装饰的类会丢失其文档字符串?

时间:2015-06-08 16:29:05

标签: python python-decorators docstring

我目前正在实现一个API,我需要在其上修饰类Wrapper,但我希望它保留其docstring以使其可供API用户使用。看一下以下最小的工作示例:

class ClassDecorator:
    """ClassDecorator docstring
    """
    def __init__(self, enableCache=True):
        self.enableCache = enableCache

    def __call__(self, wrapper):
        def numericalmathfunction(*args, **kwargs):
            func = wrapper(*args, **kwargs)
            return func
        return numericalmathfunction

@ClassDecorator(enableCache=True)
class Wrapper(object):
    """Wrapper docstring
    Instructions on how to use the Wrapper
    """
    def __init__(self, p):
        self.p = p

model = Wrapper(4)
print model.__doc__
print Wrapper.__doc__

返回

Wrapper docstring
None

Wrapper的实例确实保留了文档字符串,这很好,但Wrapper本身没有。如果用户想要了解如何使用Wrapper使用help(Wrapper),则他无法获得他想要的内容。

我知道我可以将dosctring复制粘贴到numericalmathfunction中,但装饰器将用于具有不同文档字符串的几个类。

有关如何使numericalmathfunction系统地继承包装类的文档字符串的任何想法?

1 个答案:

答案 0 :(得分:4)

使用functools.wraps()更新装饰器的属性:

from functools import wraps

class ClassDecorator:
    """ClassDecorator docstring
    """
    def __init__(self, enableCache=True):
        self.enableCache = enableCache

    def __call__(self, wrapper):
        @wraps(wrapper)                              # <-----------
        def numericalmathfunction(*args, **kwargs):
            func = wrapper(*args, **kwargs)
            return func
        return numericalmathfunction

@ClassDecorator(enableCache=True)
class Wrapper(object):
    """Wrapper docstring
    Instructions on how to use the Wrapper
    """
    def __init__(self, p):
        self.p = p

查看functools.wrap的更多标准库文档。

相关问题