Inherit docstrings in Python class inheritance

后端 未结 5 2430
难免孤独
难免孤独 2020-12-01 02:25

I\'m trying to do some class inheritance in Python. I\'d like each class and inherited class to have good docstrings. So I think for the inherited class, I\'d like it to:

5条回答
  •  春和景丽
    2020-12-01 02:56

    A mixed stile that can preserve both the inherited docstring syntax and the preferred ordering can be:

    class X(object):
      """This class has a method foo()."""
      def foo(): pass
    
    class Y(X):
      """ Also bar()."""
      __doc__ = X.__doc__ + __doc__
      def bar(): pass
    

    With the same output as Alex's one:

    >>> print Y.__doc__
    This class has a method foo(). Also bar().
    

    Thin ice: playing with docstring can make your module unusable with python -OO, expect some:

    TypeError: cannot concatenate 'str' and 'NoneType' objects
    

提交回复
热议问题