Download Inheritance in Python and more Summaries Programming Languages in PDF only on Docsity!
Inheritance in Python
Inheritance is the capability of one class to derive or inherit the properties from another
class.
Benefits of inheritance are:
It represents real-world relationships well.
It provides the reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.
Python Inheritance Syntax
Class BaseClass: {Body} Class DerivedClass(BaseClass): {Body} Creating a Parent Class
Creating a Person class with Display methods.
A Python program to demonstrate inheritance
class Person(object):
Constructor
def init(self, name, id): self.name = name self.id = id
To check if this person is an employee
def Display(self): print(self.name, self.id)
Driver code
emp = Person("Satyam", 102) # An Object of Person emp.Display()
Output:
Satyam 102 Creating a Child Class
Here Emp is another class which is going to inherit the properties of the Person class (base
class).
class Emp(Person): def Print(self): print("Emp class called") Emp_details = Emp("Mayank", 103)
calling parent class function
Emp_details.Display()
Calling child class function
Emp_details.Print()
Output:
Mayank 103 Emp class called Example of Inheritance in Python
A Python program to demonstrate inheritance
Base or Super class. Note object in bracket.
(Generally, object is made ancestor of all classes)
In Python 3.x "class Person" is
equivalent to "class Person(object)"
class Person(object):
Constructor
def init(self, name): self.name = name
To get name
def getName(self): return self.name
To check if this person is an employee
def isEmployee(self): return False
Inherited or Subclass (Note Person in bracket)
class Employee(Person):
Here we return true
def isEmployee(self): return True
Driver code
emp = Person("Geek1") # An Object of Person print(emp.getName(), emp.isEmployee()) emp = Employee("Geek2") # An Object of Employee print(emp.getName(), emp.isEmployee())
Output:
Geek1 False Geek2 True
What is object class?
Like the Java Object class, in Python (from version 3. x), the object is the root of all classes.
In Python 3.x, “class Test(object)” and “class Test” are same.
In Python 2. x, “class Test(object)” creates a class with the object as a parent (called a new-
style class), and “class Test” creates an old-style class (without an objecting parent).
Subclassing (Calling constructor of parent class)
A child class needs to identify which class is its parent class. This can be done by mentioning
the parent class name in the definition of the child class.
Eg: class subclass_name (superclass_name) :
Python code to demonstrate how parent constructors
are called.
object = B(23) print(object.name)
Output :
Traceback (most recent call last): File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in print (object.name) AttributeError: 'B' object has no attribute 'name'
Different types of Inheritance:
Single inheritance : When a child class inherits from only one parent class, it is called single
inheritance. We saw an example above.
Multiple inheritances : When a child class inherits from multiple parent classes, it is called
multiple inheritances.
Unlike java, python shows multiple inheritances.
Python example to show the working of multiple
inheritance
class Base1(object): def init(self): self.str1 = "Geek1" print("Base1") class Base2(object): def init(self): self.str2 = "Geek2" print("Base2") class Derived(Base1, Base2): def init(self):
Calling constructors of Base
and Base2 classes
Base1.init(self) Base2.init(self) print("Derived") def printStrs(self): print(self.str1, self.str2) ob = Derived() ob.printStrs()
Output:
Base Base Derived Geek1 Geek
Multilevel inheritance : When we have a child and grandchild relationship.
A Python program to demonstrate inheritance
Base or Super class. Note object in bracket.
(Generally, object is made ancestor of all classes)
In Python 3.x "class Person" is
equivalent to "class Person(object)"
class Base(object):
Constructor
def init(self, name): self.name = name
To get name
def getName(self): return self.name
Inherited or Sub class (Note Person in bracket)
class Child(Base):
Constructor
def init(self, name, age): Base.init(self, name) self.age = age
To get name
def getAge(self): return self.age
Inherited or Sub class (Note Person in bracket)
class GrandChild(Child):
Constructor
def init(self, name, age, address): Child.init(self, name, age) self.address = address
To get address
def getAddress(self): return self.address
Driver code
g = GrandChild("Geek1", 23, "Noida") print(g.getName(), g.getAge(), g.getAddress())
Output:
Geek1 23 Noida
Hierarchical inheritance More than one derived class are created from a single base.
Hybrid inheritance : This form combines more than one form of inheritance. Basically, it is a
blend of more than one type of inheritance.
Private members of the parent class
We don’t always want the instance variables of the parent class to be inherited by the child
class i.e. we can make some of the instance variables of the parent class private, which won’t
be available to the child class.
We can make an instance variable private by adding double underscores before its name. For
example,