Inheritance in Python
Table of Content:
What is Inheritance?
-
Inheritance
describesis a kind of
relationship between two or more classes, abstracting common details into super class and storing specific ones in the subclass. -
To create a child class, specify the parent class name inside the pair of parenthesis, followed by it's name.
Example
class Child(Parent): pass
- Every child class inherits all the behaviours exhibited by their parent class.
Inheritance
-
In Python, every class uses inheritance and is inherited from
object
by default. -
Hence, the below two definitions of
MySubClass
are same.
Definition 1
class MySubClass:
pass
Definition 2
class MySubClass(object):
pass
-
object
is known as parent or super class. -
MySubClass
is known as child or subclass or derived class.
Inheritance in Action
class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
class Employee(Person):
all_employees = []
def __init__(self, fname, lname, empid):
Person.__init__(self, fname, lname)
self.empid = empid
Employee.all_employees.append(self)
Employee
class is derived fromPerson
.
Inheritance in Action
p1 = Person('George', 'smith')
print(p1.fname, '-', p1.lname)
e1 = Employee('Jack', 'simmons', 456342)
e2 = Employee('John', 'williams', 123656)
print(e1.fname, '-', e1.empid)
print(e2.fname, '-', e2.empid)
Output
George - smith
Jack - 456342
John - 123656
- In the above example,
Employee
class utilizes__init __
method of the parent classPerson
to create its object.
Extending Built-in Types
-
Inheritance
feature can be also used to extend the built-in classes likelist
ordict
. -
The following example extends
list
and createsEmployeesList
, which can identify employees, having a given search word in their first name.
Example 1
class EmployeesList(list): def search(self, name): matching_employees = [] for employee in Employee.all_employees: if name in employee.fname: matching_employees.append(employee.fname) return matching_employees
Extending Built-in Types
Extending Built-in Types EmployeesList
object can be used to store all employee objects, just by replacing statement all_employees = []
with all_employees = EmployeesList()
.
Example 2
class Employee(Person): all_employees = EmployeesList() def __init__(self, fname, lname, empid): Person.__init__(self, fname, lname) self.empid = empid Employee.all_employees.append(self) e1 = Employee('Jack', 'simmons', 456342) e2 = Employee('George', 'Brown', 656721) print(Employee.all_employees.search('or'))
Output
['George']