Python method overriding
Python Method Overriding
You can always override a superclass method. One reason to override a superclass method is that you might want to use special or different functionality in your subclass.
Example
class Parent: # define parent class
def myMethod(self):
print ('Calling parent method')
class Child(Parent): # define child class
def myMethod(self):
print ('Calling child method')
c = Child() # instance of child
c.myMethod() # child calls overridden method
When the above code is executed, it produces the following output –
Calling child method
To understand inheritance in Python, let’s take another example. We use the following Employee class as the parent 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
Next, we define a SalesOfficer class that uses Employee as its parent class. It inherits the instance variables name and salary from the parent class. In addition, the child class has an additional instance variable called incentive.
We will use the built-in function super(), which returns a reference to the parent class, and call the parent class constructor from the child class’s init() method.
class SalesOfficer(Employee):
def __init__(self,nm, sal, inc):
super().__init__(nm,sal)
self.incnt=inc
def getSalary(self):
return self.salary+self.incnt
The getSalary() method is overridden to add an incentive to the salary.
Example
Declare objects of the parent and child classes and see the effects of the override. The complete code is as follows-
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
class SalesOfficer(Employee):
def __init__(self, nm, sal, inc):
super().__init__(nm,sal)
self.incnt=inc
def getSalary(self):
return self.salary+self.incnt
e1=Employee("Rajesh", 9000)
print ("Total salary for {} is Rs {}".format(e1.getName(),e1.getSalary()))
s1=SalesOfficer('Kiran', 10000, 1000)
print ("Total salary for {} is Rs {}".format(s1.getName(),s1.getSalary()))
When you execute this code, it will produce the following output.
Total salary for Rajesh is Rs 9000
Total salary for Kiran is Rs 11000
Basic Overridable Methods
The following table lists some common functions of the Object class, which is the parent class of all Python classes. You can override these methods in your own classes −
Number | Method, Description, and Example |
---|---|
1 | __init__ ( self [,args...] ) Constructor (optional arguments) Example call: obj = className(args) |
2 | __del__( self ) Destructor, deletes an object Example call: del obj |
3 | __repr__( self ) Computable string representation Example call: repr(obj) |
4 | __str__( self ) Printable string representation. Example call: str(obj) |