Python 为什么装饰类会松开其docstring?

Python 为什么装饰类会松开其docstring?,python,python-decorators,docstring,Python,Python Decorators,Docstring,我目前正在实现一个API,在这个API上我需要修饰类包装器,但我希望它保留其docstring,以便API用户可以使用它。请看以下最小工作示例: class ClassDecorator: """ClassDecorator docstring """ def __init__(self, enableCache=True): self.enableCache = enableCache def __call__(self, wrapper):

我目前正在实现一个API,在这个API上我需要修饰类
包装器
,但我希望它保留其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
的实例确实保留了docstring,这很好,但是
Wrapper
本身没有。如果用户想学习如何使用
Wrapper
使用
help(Wrapper)
,他就得不到想要的东西

我知道我可以将剂量复制粘贴到
numericalmathfunction
,但decorator将用于具有不同docstring的几个类

关于如何使
numericalmathfunction
系统地继承包装类的docstring,您有什么想法吗?

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

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导入包装
类装饰器:
“”“ClassDecorator docstring”
"""
def uuu init uuuu(self,enableCache=True):
self.enableCache=enableCache
定义调用(self,wrapper):

@包装(wrapper)#因为从技术上讲,包装现在是首先被调用的类。查看
@wrapps
太好了,它很有效。是否有类似的解决方案使修饰函数继承类属性?我已经找到了一个解决方案(请参阅),但我想知道是否有类似于
@wrapps
的东西。我不知道。您可以根据该链接中的答案轻松编写包装器装饰器,并在任何地方使用它。这应该与
@wrapps
的工作方式相同。好的,我稍后会尝试这样做,以使代码更加优雅。目前,我已经有了一个有效的解决方案。Thanks@FelipeAguirre对于这类工作的一些很好的例子,请观看。特别是前30分钟。我会看一看,但我仍然坚持使用python 2,教程是针对python 3的:(