top of page
Search
Writer's pictureMaia

Python Tips Series: Inheritance


Inheritance is a very key concept of object oriented programming (OOP). Python supports inheritance too.

So, what is inheritance? Inheritance allows us to define a class that inherits all the methods and properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Let's create some empty classes that show inheritance to explore some of the basics about inheritance.

We can use issubclass() function to check if a class inherits from another class.

We see Square inherits from Rectangle, Rectangle inherits from Polygon, and Polygon inherits from Shape, so Square is inherited from Shape (indirectly).

However, Square does not inherits from Ellipse, but they both inherit from Shape, one directly and another indirectly.

We also see that in Python object class is the root of all objects. Any object in Python either directly or indirectly inherits from object class.

Object is a built-in class in Python.

We already know that in Python everything are objects, including functions and other things. So, is function a subclass of object class? The answer is of course: yes.

When we define a subclass we can re-define or override some of the functions or behaviors. If we don't override a function, it will inherit or keep the same from the parent class.

In child class, we can also extend or add new functions which only available in subclass. If we try to call these functions in parent class, it will be error.

Also, in subclass we can always call any parent class's function by using the super() method to access to the parent object. We do this to delegate some of the work to the parent object which are already implemented, so that we don't have to duplicate the work again. This is the core meaning of inheritance.


That's all about key ideas of Python Inheritance.


Happy Inheriting!



Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page