Sling Academy
Home/Python/Python: How to Override Methods in Classes

Python: How to Override Methods in Classes

Last updated: February 19, 2024

Introduction

Python’s object-oriented programming allows you to structure your code in a more reusable and structured way. One of the key concepts in object-oriented programming is method overriding, which allows a child class to provide a specific implementation of a method that is already provided by one of its parent classes. This tutorial will cover how to override methods in classes in Python, providing clarity with examples and best practices.

Understanding Method Overriding

Method overriding occurs when a child class defines a method that already exists in its parent class. This is useful when you want the child class to perform a different or additional action than what is implemented by the method in the parent class. In Python, overriding is accomplished simply by defining in the child class a method with the same name as the method to be overridden in the parent class.

Basic Method Overriding

class Parent:
    def my_method(self):
        print('Calling parent method')

class Child(Parent):
    def my_method(self):
        print('Calling child method')

child = Child()
child.my_method()

This will output:

Calling child method

In this basic example, the Child class overrides the my_method of the Parent class. When my_method is called on an instance of Child, the implementation in Child is executed rather than that in Parent.

Using super() to Extend Functionality

In some cases, you might want to call the original parent method before or after executing your overriding code to ensure that the parent class’s method functionality is not lost. This can be achieved with the super() function.

class Parent:
    def my_method(self):
        print('Parent method')

class Child(Parent):
    def my_method(self):
        super().my_method()
        print('Child method')

child = Child()
child.my_method()

This results in:

Parent method
Child method

Here, the Child class’s my_method first calls the Parent class’s my_method using super(), then proceeds to its own implementation. This way, the overriding method in the Child class extends the functionality of the original method in the Parent class.

Overriding Special Methods

Python classes can also override special (or “magic”) methods. These are methods with double underscores at the beginning and end of their names, such as __init__ for constructors, __str__ for the string representation, and __add__ for operator overloading. Overriding these allows for more nuanced and Pythonic handling of class objects.

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def __str__(self):
        return f'Rectangle({self.width}, {self.height})'

class Square(Rectangle):
    def __init__(self, side):
        super().__init__(side, side)

    def __str__(self):
        return f'Square(side={self.side})'

By overriding the __init__ and __str__ methods, the Square class automatically inherits all attributes and methods from Rectangle but specifies different behaviors suited to squares specifically.

Best Practices for Method Overriding

  • Use super() judiciously: Remember that super() is not just for calling methods in the immediate parent class; it’s for ensuring the correct, cooperative call order among all classes in the hierarchy, respecting the method resolution order (MRO).
  • Keep the overriding method’s signature consistent: Though Python is dynamically typed, maintaining a consistent signature (e.g., parameter names and expected types) helps with code readability and maintainability.
  • Enhance, don’t fundamentally change: When overriding methods, aim to either extend or refine the behavior of the parent class’s method, rather than completely replacing its intended functionality.

Conclusion

Method overriding is a fundamental concept in Python’s object-oriented programming that allows for more flexible and powerful class hierarchies. By understanding and applying the principles of method overriding, developers can create more customizable and maintainable code. Remember, the goal of method overriding should be to enhance and extend the functionality of parent class methods, not to alter their fundamental behavior.

Previous Article: 4 ways to install Python modules on Windows without admin rights

Series: Basic Python Tutorials

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs