DEV Community

waltertaya
waltertaya

Posted on

Simple way to master inheritance in Python

Inheritance is mechanism that allows a class to inherit properties and attributes from another class.
General Syntax of inheritance

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>
Enter fullscreen mode Exit fullscreen mode

The name BaseClassName(super class) must be defined in a namespace accessible from the scope containing the derived class definition.
If the super class is defined in another module then the syntax is:
class DerivedClassName(moduleName.BaseClassName):

How inheritance work?
Execution of a derived class definition proceeds the same as for a base class. When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.

Method Overriding

Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively virtual.)

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call

BaseClassName.methodname(self, arguments)

This is occasionally useful to clients as well. (Note that this only works if the base class is accessible as BaseClassName in the global scope.)

Built Functions that works with inheritance

  1. isinstance() to check an instance's type:
isinstance(obj, int)
Enter fullscreen mode Exit fullscreen mode

will return True iff obj.__class__ is int or some class derived from int.

  1. issubclass() to check class inheritance:
issubclass(bool, int)
Enter fullscreen mode Exit fullscreen mode

will return True since bool is a subclass of int.

Multiple Inheritance

Python supports a form of multiple inheritance as well.
Syntax

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)