Implementing a class property that preserves the docstring

前端 未结 2 1568
长发绾君心
长发绾君心 2021-01-19 08:09

I have a descriptor that turns a method into a property on the class level:

class classproperty(object):

    def __init__(self, getter):
        self.getter         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-19 08:51

    If you jump through a few hoops, it can be retrieved, but not directly through the property itself like A.test.__doc__ because of the way descriptors work.

    class classproperty(object):
        def __init__(self, getter):
            self.getter = getter
    
        def __get__(self, instance, owner):
            if instance is None:  # instance attribute accessed on class?
                return self
            return self.getter(owner)
    
    class A(object):
        @classproperty
        def test(cls):
            "test's docstring"
            return "Test"
    
    def docstring(cls, methodname):
        return getattr(cls, methodname).getter.__doc__
    
    print docstring(A, 'test')  # -> test's docstring
    

提交回复
热议问题