Skip to main content
Published on

Inheritance in Python

Share:

Introduction

Inheritance is a fundamental pillar of object-oriented programming (OOP). It allows you to create a new class from an existing one, reusing and expanding its functionality.

Understanding Inheritance

When talking about inheritance, we refer to the mechanism by which a class inherits attributes and methods from another class. The class that is inherited from is called a "superclass" or "base class", while the class that inherits is called a "subclass" or "derived class".

Benefits of Inheritance

  • Code Reuse: There is no need to rewrite the same code repeatedly.
  • Extensibility: It is easy to add more functionality to the subclass, if needed.
  • Hierarchy: It establishes a logical way to organise code, representing "is-a" relationships.

Basic Syntax

class SuperClass:
  pass

class SubClass(SuperClass):
  pass

In the previous example, SubClass inherits from SuperClass.

Practical Example

class Parent:
  lastName = 'Silva'

  def favoriteFood(self):
    print('My favorite food is seafood rice.')

class Child(Parent):
  firstName = 'Nelson'
  age = 28

  def information(self):
    print('Name:', self.firstName, self.lastName)
    print('Age:', self.age)

person = Child()
person.information()
person.favoriteFood()

In this example, the Child class inherits both the lastName attribute and the favoriteFood() method from the Parent class.

Conclusion

Inheritance in Python offers a structured and efficient way to create and manage classes, allowing subclasses to benefit from and expand the functionality of superclasses. Understanding this concept is essential for anyone who wants to deepen their knowledge of object-oriented programming in Python.

Happy coding!