Python OOP Tutorial – 2. Inheritance

By inheritance having already a class we can define a derived class from it, which 

will have all methods and attributes of the initial class, and in plus new methods and attributes.

The class from which we will define other classes is named base class, super class or parent class. 

New class defined using inheritance is named derived class, subclass or child class.

Using inheritance code is simplified and reuse code fragments (using derived class 

we can create new objects, for which we don't need to write code for attributes 

and methods from base class). We write code only for aditional attributes and methods from 

derived class.

Lets take an example of a company in which generic are working employes, but those can be 

regular employees, students, managers, contributors even freelancers. So we can define a base class 

named Employee which will contain a common set of attributes and methods that are for all mettioned prior. 

Then we can derive from base class Employee, classes named RegularEmployee, Student, Manager, Contributor, Freelancer 

Here is the code for base class Employee: 

class Employee:

def __init__(self, name, phone, departament):

self.name = name

self.phone = phone

self.departament = departament


def printemp(self):

print(self.name, self.phone, self.departament)


jd=Employee("John", "021111111", "IT")

jd.printemp()

print(jd.name)


#Output:

John Doe 021111111 IT

John Doe

We can create a class that inherit Employee and which have in plus attribute trainingStage which value show that employee is student 

Here is code with added derived class: 

class Employee:

def __init__(self, name, phone, departament):

self.name = name

self.phone = phone

self.departament = departament


def printemp(self):

print(self.name, self.phone, self.departament)


#inheritance

class Student(Employee):

trainingStage='undergraduate student'


jt=Student("John Trevor", "02122222", "Sales")

jt.printemp()

print(jt.trainingStage)

print(jt.name)


#output: 

John Trevor 02122222 Sales

student

John Trevor

We see inherited class Student have like "argument" initial or base class Employee

means general rule is 

class DerivedClass(BaseClass1, BaseClass2):

    <statement>

    .

    .

There is BaseClass1, BaseClass2, ... i.e inherited class can inherit from many base classes.

In code from above "jt" is a Student object. Class Student don't contain anything about attribute name, but 

because Student inherit Employee class, which have attribute name, then print(jt.name) , i.e. jt.name make sense, 

it will print name attribute from base class. When we try to access an attribute from inherited class, if attribute 

is in inherited class definition, it will be used, otherwhise it is used attribute from base class. Similar 

principle apply from methods. First python interpretor looks for method in inherited class, then if it not 

find it, then will check in base class.