Search notes:

Python: class derivation

Python allows to derive (child-)classes from parent/base classes.
In the declaration of the derived class, the name of the base class appears in parentheses after the name of the derived class.
When a method is called on the derived class without overriding it, the base class' method (with the same name) will be called
class Base:
      def m(self):
          print('Base::m')

class Deriv(Base):
      pass

d = Deriv()
d.m()
Github repository about-Python, path: /class/derivation/simple.py

Overriding methods in derived classes

The following example tries to demonstrate how methods might be overridden in derived classes:
class Base:
      def m(self):
          print('Base::m')

class Deriv(Base):
      def m(self):
          print('Deriv::m')

b = Base ()
d = Deriv()

b.m()
d.m()
Github repository about-Python, path: /class/derivation/overriding-methods.py

Calling methods of base classes

A method is able to call a base class's method using the super() built-in function.

See also

multiple inheritance
A use case of deriving classes is to derive from an exception class to create user defined exceptions.

Index