Skip to main content
 首页 » 编程设计

python之如何使用装饰器自动记录我的类属性

2025年05月04日12kerrycode

假设我有两个类(A 和B),其中第二个类派生自第一个类。此外,我通过在 B 中编写新实现来隐藏 A 中实现的一些属性。但是,我为 A 编写的文档字符串对 B 仍然有效,而且我很懒——我不想复制粘贴所有内容。

请注意,这里的一个关键问题是我的目标是属性,对于一般的类方法,已经发布了解决方案。

在代码中,类的最小示例可能如下所示:

In [1]: class A(object): 
   ...:     @property 
   ...:     def a(self): 
   ...:         "The a:ness of it" 
   ...:         return True 
   ...:      
 
In [2]: class B(A): 
   ...:     @property 
   ...:     def a(self): 
   ...:         return False 
   ...:      

我基本上想要的是有一种方法来实现以下目标:

In [8]: B.a.__doc__ 
Out[8]: 'The a:ness of it' 

实际上 B.a 的文档字符串是空的,写入 B.a.__doc__ 是不可能的,因为它会引发 TypeError。

据我所知,以下是一个解决方案:

from inspect import getmro 
 
def inheritDocFromA(f): 
    """This decorator will copy the docstring from ``A`` for the 
    matching function ``f`` if such exists and no docstring has been added 
    manually. 
    """ 
    if f.__doc__ is None: 
 
        fname = f.__name__ 
 
        for c in getmro(A): 
            if hasattr(c, fname): 
                d = getattr(c, fname).__doc__ 
                if d is not None: 
                    f.__doc__ = d 
                    break 
 
    return f 

这确实有效,但是非常丑陋,因为我发现 A 被硬编码到装饰器函数中 当传递给装饰器时,无法知道 f 附加到哪个类:

In [15]: class C(A): 
   ....:     @property 
   ....:     @inheritDocFromA 
   ....:     def a(self): 
   ....:         return False 
   ....:      
 
In [16]: C.a.__doc__ 
Out[16]: 'The a:ness of it' 

问题: 是否可以为类属性上的装饰器应用文档字符串构造一个通用解决方案,而无需在继承到装饰器函数中进行硬编码?

我也尝试过装饰类,但后来我碰壁了,因为属性文档字符串被写保护了。

最后,如果可能的话,我希望该解决方案同时适用于 Python 2.7 和 3.4。

请您参考如下方法:

可以编写一个装饰器,在通过类访问时返回正确的 __doc__ — 毕竟,__get__ 接收类型并可以通过其 MRO,找到适当的 __doc__,并将其设置在自身上(或在为此目的创建和返回的代理上)。但是解决 __doc__ 不可写的问题要简单得多。

事实证明,由于 property 是作为一种类型实现的,因此使其实例的 __doc__ 可写就像继承它一样简单:

class property_writable_doc(property): 
    pass 

那么您使用类装饰器继承属性的 __doc__ 的想法就可以工作了:

def inherit_doc_class(cls): 
    for name, obj in cls.__dict__.iteritems(): 
        if isinstance(obj, property_writable_doc) and obj.__doc__ is None: 
            for t in cls.__mro__: 
                if name in t.__dict__ and t.__dict__[name].__doc__ is not None: 
                    obj.__doc__ = t.__dict__[name].__doc__ 
                    break 
    return cls 
 
class A(object): 
    @property 
    def a(self): 
        "The a:ness of it" 
        return True 
 
@inherit_doc_class 
class B(A): 
    @property_writable_doc 
    def a(self): 
        return False 
 
@inherit_doc_class 
class C(A): 
    @property_writable_doc 
    def a(self): 
        "The C:ness of it" 
        return False