Understanding method overriding with Python

It is called method overriding to a new definition created within a class, for one or more methods inherited from its superclass.
The following example shows how to do it. This example is based on this previous entry: Understanding OOP Inheritance with Python

To override the inherited constructor of the Person class, follow these steps:
Enter a new declaration of the constructor method within the Employee class.
Add the parameters name,lastname,birthdate,department,email. Within the definition of the constructor add the attributtes self.name, self.lastname,self.birthdate,self.department and self.email then assign the corresponding parameters.
Add the following print instruction to the end of the constructor.

Fig 1. Modified constructor

In the main program add two new lines with the following two phrases:

"John works in department"

and concatenate the department attribute of the object John, with a period and

"John's email is "

and concatenate the email attribute of the object John with a period.

Fig 2. Main program

Run the code. As you can see the Jonh instance of the Employee class now accepts three parameters, because the Person constructor has been overriding.
In addition, the talk method remains the same inherited from Person.

Fig 3. Running the example
$ py SampleOverriding.py

Download example source code.

Understanding OOP Inheritance with Python

One of the most common goals for the OOP is code reusability.
Characteristics such as inheritance contributes to achieving this goal.


Inheritance is the most used mechanism to optimise the coding, since it allows
to reuse methods defined in superclasses, to define new subclasses.
The following example uses the class Person as its superclass.

Fig 1. Inheritance
Fig 2. Person Class

We know that a person also can be an employee in addition to talking, and Employee can show its earnings so we will
declare a class called Employee.

Fig 3. Employee Class

Who inherits the talk() method of the Person class to implement inheritance in
this example:

Fig 4. Main program

You will notice how the “John” object, which is now an instance of Employee
continues to behave as an instance of Person because it has inherited its

Fig 4. Run the example
$ py Sample1OOP.py

Download example source code.