【问题标题】:docstring that works with a Python class property?与 Python 类属性一起使用的文档字符串?
【发布时间】:2012-01-04 00:14:37
【问题描述】:

我在下面定义了一个类,它有一个名为“prop”的类属性,我希望打印出文档字符串“这是一个属性注释”。当前行为执行属性的 getter 并打印“getter”。

有没有办法设置类及其元类,以便我可以键入“help(MyClass.prop)”并获取文档字符串?

class _Metaclass(type):
    @property
    def prop(cls):
        """this is a property comment"""
        print("getter")
        return 1
    @prop.setter
    def prop(cls,value):
        print("setter")

class MyClass(metaclass=_Metaclass):
    """this is a class comment"""
    def func():
        """this is a function comment"""

【问题讨论】:

    标签: python python-3.x docstring


    【解决方案1】:

    您已经在元类上设置了一个属性。因此,当您执行MyClass.prop 时,您实际上是在执行MyClass 类对象上的属性。如果这是在普通类而不是元类上,则将从 getter 方法正确定义文档字符串。元类之于类就像类之于实例一样,如果这有助于您思考这里发生了什么。您应该从help(_Metaclass.prop) 获得正确的文档字符串。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 2014-06-12
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2018-11-28
    相关资源
    最近更新 更多