Inheritance and Special Methods
Examples
File 9 appendix/inherit.py
Superclass
Subclass
appendix.inherit.
Sub
(
)
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-12-20 10:02:20 (15.0ms) python3 (1.14s)
('Function.', 'Function.')
Sub.func.__doc__, inspect.getdoc(Sub.func)
[3] 2020-12-20 10:02:20 (13.0ms) python3 (1.15s)
(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-12-20 10:02:20 (12.0ms) python3 (1.16s)
(None, 'Call self as a function.')
Sub.__repr__.__doc__, inspect.getdoc(Sub.__repr__)
[5] 2020-12-20 10:02:20 (14.7ms) python3 (1.18s)
(None, 'Return repr(self).')
Sub.__repr__.__doc__, inspect.getdoc(Sub.__repr__)
[6] 2020-12-20 10:02:20 (13.4ms) python3 (1.19s)
(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-12-20 10:02:20 (13.0ms) python3 (1.20s)
__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.