Inheritance and Special Methods

Examples

File 9 appendix/inherit.py

class Base:
    """Base class."""

    def func(self):
        """Function."""


class Sub(Base):
    """Subclass."""

    # Should be added.
    def func(self):
        pass

    # Should not be added.
    def __call__(self):
        pass

    # Should not be added.
    def __repr__(self):
        pass

    # Should not be added.
    def __str__(self):
        pass

    # and so on.

Superclass

![mkapi](appendix.inherit.Base)
class
appendix.inherit.Base()

Base class.

Methods
  • func() Function.
method
func()

Function.

Subclass

![mkapi](appendix.inherit.Sub)
class
appendix.inherit.Sub()
Bases
appendix.inherit.Base

Subclass.

Methods
  • func() Function.
method
func()

Function.

Implementation

There are two ways to get docstring: __doc__ attribute or inspect.getdoc().

import inspect
from appendix.inherit import Base, Sub

Base.func.__doc__, inspect.getdoc(Base.func)

[2] 2020-06-09 15:42:11 (5.00ms) python3 (432ms)

('Function.', 'Function.')
Sub.func.__doc__, inspect.getdoc(Sub.func)

[3] 2020-06-09 15:42:11 (3.00ms) python3 (435ms)

(None, 'Function.')

Because Sub.func() has no docstring, its __doc__ attribute is None. On the other hand, the super class Base.func() has docstring, so that you can get the inherited docstring using inspect.getdoc(). Therefore, MkApi uses inspect.getdoc().

Now, let's see some special methods:

Sub.__call__.__doc__, inspect.getdoc(Sub.__call__)

[4] 2020-06-09 15:42:11 (3.00ms) python3 (438ms)

(None, 'Call self as a function.')
Sub.__repr__.__doc__, inspect.getdoc(Sub.__repr__)

[5] 2020-06-09 15:42:11 (3.00ms) python3 (441ms)

(None, 'Return repr(self).')
Sub.__repr__.__doc__, inspect.getdoc(Sub.__repr__)

[6] 2020-06-09 15:42:11 (3.00ms) python3 (444ms)

(None, 'Return repr(self).')

These docstrings come from object.

for name, obj in object.__dict__.items():
    doc = obj.__doc__
    if doc and '\n' not in doc:
        print(f"{name}: {doc}")

[7] 2020-06-09 15:42:11 (3.00ms) python3 (447ms)

__repr__: Return repr(self).
__hash__: Return hash(self).
__str__: Return str(self).
__getattribute__: Return getattr(self, name).
__setattr__: Implement setattr(self, name, value).
__delattr__: Implement delattr(self, name).
__lt__: Return self<value.
__le__: Return self<=value.
__eq__: Return self==value.
__ne__: Return self!=value.
__gt__: Return self>value.
__ge__: Return self>=value.
__init__: Initialize self.  See help(type(self)) for accurate signature.
__new__: Create and return a new object.  See help(type) for accurate signature.
__reduce_ex__: Helper for pickle.
__reduce__: Helper for pickle.
__format__: Default object formatter.
__sizeof__: Size of object in memory, in bytes.
__dir__: Default dir() implementation.
__class__: the object's class

If docstring of an object is equal to that of object, the object doesn't be added into API documentation.