OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
Last Updated :
07 Jun, 2022
We have discussed following topics on Object Oriented Programming in Python
In this article, Inheritance is introduced.
One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanisms to achieve the same. In inheritance, a class (usually called superclass) is inherited by another class (usually called subclass). The subclass adds some attributes to superclass.
Below is a sample Python program to show how inheritance is implemented in Python.
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 employee
def isEmployee(self):
return False
# Inherited or Sub class (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)
How to check if a class is subclass of another?
Python provides a function issubclass() that directly tells us if a class is subclass of another class.
Python
# Python example to check if a class is
# subclass of another
class Base(object):
pass # Empty Class
class Derived(Base):
pass # Empty Class
# Driver Code
print(issubclass(Derived, Base))
print(issubclass(Base, Derived))
d = Derived()
b = Base()
# b is not an instance of Derived
print(isinstance(b, Derived))
# But d is an instance of Base
print(isinstance(d, Base))
Output:
True
False
False
True
What is object class?
Like Java Object class, in Python (from version 3.x), object is 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 object as parent (called new style class) and "class Test" creates old style class (without object parent). Refer
this for more details.
Does Python support Multiple Inheritance?
Unlike Java and like C++, Python supports multiple inheritance. We specify all parent classes as comma separated list in bracket.
Python
# Python example to show 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 Base1
# and Base2 classes
Base1.__init__(self)
Base2.__init__(self)
print "Derived"
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()
Output:
Base1
Base2
Derived
('Geek1', 'Geek2')
How to access parent members in a subclass?
- Using Parent class name
Python
# Python example to show that base
# class members can be accessed in
# derived class using base class name
class Base(object):
# Constructor
def __init__(self, x):
self.x = x
class Derived(Base):
# Constructor
def __init__(self, x, y):
Base.x = x
self.y = y
def printXY(self):
# print(self.x, self.y) will also work
print(Base.x, self.y)
# Driver Code
d = Derived(10, 20)
d.printXY()
- Using super()
We can also access parent class members using super.
Python
# Python example to show that base
# class members can be accessed in
# derived class using super()
class Base(object):
# Constructor
def __init__(self, x):
self.x = x
class Derived(Base):
# Constructor
def __init__(self, x, y):
''' In Python 3.x, "super().__init__(name)"
also works'''
super(Derived, self).__init__(x)
self.y = y
def printXY(self):
# Note that Base.x won't work here
# because super() is used in constructor
print(self.x, self.y)
# Driver Code
d = Derived(10, 20)
d.printXY()
Note that the above two methods are not exactly the same. In the next article on inheritance, we will covering following topics.
1) How super works? How accessing a member through super and parent class name are different?
2) How Diamond problem is handled in Python?
Exercise:
Predict the output of following Python programs
-
Python
class X(object):
def __init__(self, a):
self.num = a
def doubleup(self):
self.num *= 2
class Y(X):
def __init__(self, a):
X.__init__(self, a)
def tripleup(self):
self.num *= 3
obj = Y(4)
print(obj.num)
obj.doubleup()
print(obj.num)
obj.tripleup()
print(obj.num)
-
Python
# Base or Super class
class Person(object):
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def isEmployee(self):
return False
# Inherited or Subclass (Note Person in bracket)
class Employee(Person):
def __init__(self, name, eid):
''' In Python 3.0+, "super().__init__(name)"
also works'''
super(Employee, self).__init__(name)
self.empID = eid
def isEmployee(self):
return True
def getID(self):
return self.empID
# Driver code
emp = Employee("Geek1", "E101")
print(emp.getName(), emp.isEmployee(), emp.getID())
Output:
('Geek1', True, 'E101')
Similar Reads
Understanding the Role of Parent Class's init() in Python Inheritance In object-oriented programming (OOP) inheritance allows classes to inherit attributes and methods from other classes. This enables code reuse and the creation of complex systems. When creating a new class (child) from an existing class (parent) a common question is whether the __init__() method of t
3 min read
Python | super() in single inheritance Prerequisites: Inheritance, function overriding At a fairly abstract level, super() provides the access to those methods of the super-class (parent class) which have been overridden in a sub-class (child class) that inherits from it. Consider the code example given below, here we have a class named
6 min read
Python Multiple Inheritance With super() Function We are given some classes and our task is to find out how super() function works with multiple inheritance in Python. In this article, we will see how Python super() works with Multiple Inheritance. Python Multiple Inheritance With super() Below, are examples of how Python's Super() Work with Multip
2 min read
Inheritance and Composition in Python Prerequisite - Classes and Objects in Python This article will compare and highlight the features of is-a relation and has-a relation in Python. What is Inheritance (Is-A Relation)? It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all the propertie
4 min read
Calling a Super Class Constructor in Python Classes are like creating a blueprint for an object. If we want to build a building then we must have the blueprint for that, like how many rooms will be there, its dimensions and many more, so here the actual building is an object and blueprint of the building is a class. A Class is a user-defined
4 min read
Data Classes in Python | Set 4 (Inheritance) Prerequisites: Inheritance In Python, Data Classes in Python | Set 3 In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited. Python3 1== from dataclasses import data
2 min read
How to Check the Type of an Object in Python In this article, we will explore the essential skill of determining the type of an object in Python. Before engaging in any operations on an object within the Python programming language, it is imperative to possess the knowledge of how to check its type. This fundamental task is encountered regular
4 min read
Inheritance in Python | Set 2 Prerequisite : basics of inheritance in Python, Inheritance, examples of object, issubclass and super There are 2 built-in functions in Python that are related to inheritance. They are: 1. isinstance(): It checks the type of an object. Its syntax is: isinstance(object_name, class_name) It would retu
4 min read
Python | super() function with multilevel inheritance super() function in Python: Python super function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'. To understand Python super function we m
3 min read
How to create an instance of a Metaclass that run on both Python2 and Python3? Metaclasses are classes that generate other classes. It is an efficient tool for class verification, to prevent sub class from inheriting certain class function, and dynamic generation of classes. Here we will discuss how to create an instance of a Metaclass that runs on both Python 2 and Python 3.
3 min read