Python Method Overriding: Customizing Subclass Behavior

Discover how method overriding works in Python, where a subclass defines a method with the same name as its superclass. Learn how Python determines which method to call at runtime and how to customize functionality in your subclass.



Python - Method Overriding

Method overriding in Python means defining a method in a subclass with the same name as a method in its superclass. At runtime, Python decides which method to call based on the object.

You can override parent class methods to provide different functionality in your subclass.

Example: Overriding a Method

# Define parent class
class Parent: 
   def myMethod(self):
      print('Calling parent method')

# Define child class
class Child(Parent): 
   def myMethod(self):
      print('Calling child method')

# Instance of child
c = Child() 
# Child calls overridden method
c.myMethod()
        
Output

Calling child method
        

Here’s another example using Employee and SalesOfficer classes:

Example: Employee and SalesOfficer

# Define Employee class
class Employee:
   def __init__(self, nm, sal):
      self.name = nm
      self.salary = sal
   def getName(self):
      return self.name
   def getSalary(self):
      return self.salary

# Define SalesOfficer class
class SalesOfficer(Employee):
   def __init__(self, nm, sal, inc):
      super().__init__(nm, sal)
      self.incnt = inc
   def getSalary(self):
      return self.salary + self.incnt

# Create instances
e1 = Employee("Suresh", 8000)
print("Total salary for {} is Rs {}".format(e1.getName(), e1.getSalary()))
s1 = SalesOfficer("Mahesh", 10000, 1500)
print("Total salary for {} is Rs {}".format(s1.getName(), s1.getSalary()))
        
Output

Total salary for Suresh is Rs 8000
Total salary for Mahesh is Rs 11500
        

Base Overridable Methods

The table below lists some common methods from the object class that can be overridden:

Method Description & Sample Call
__init__(self [,args...]) Constructor (with optional arguments)
Sample Call: obj = className(args)
__del__(self) Destructor, deletes an object
Sample Call: del obj
__repr__(self) Evaluatable string representation
Sample Call: repr(obj)
__str__(self) Printable string representation
Sample Call: str(obj)