13.10. Inheritance

Inheritance describes how the attributes of base classes are “bequeathed” to a derived class. A subclass inherits attributes of any of its base classes whether they be data attributes or methods.

We present an example below. P is a simple class with no attributes. C is a class with no attributes which derives from (and therefore is a subclass of) P:

>>> class P:                      # parent class
…       pass
>>> class C(P):                   # child class
…       pass
>>>
>>> c = C()                       # instantiate child
>>> c.__class__                   # child "is a" parent
<class __main__.C at 8120c98>
>>> C.__bases__                   # child's parent class(es)
(<class __main__.P at 811fc98>,)

Because P has no attributes, nothing was inherited by C. Let us make our example more useful by giving P some attributes:

 >>> ...

Get Core Python Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.