OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super) - GeeksforGeeks

10 Feb, 2020
We have discussed following topics on Object Oriented Programming in Python
Object Oriented Programming in Python | set-1
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
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.
   # 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 codeemp = Person("Geek1")  # An Object of Personprint(emp.getName(), emp.isEmployee())  emp = Employee("Geek2") # An Object of Employeeprint(emp.getName(), emp.isEmployee())
('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 example to check if a class is# subclass of another  class Base(object):    pass   # Empty Class  class Derived(Base):    pass   # Empty Class  # Driver Codeprint(issubclass(Derived, Base))print(issubclass(Base, Derived))  d = Derived()b = Base()  # b is not an instance of Derivedprint(isinstance(b, Derived))  # But d is an instance of Baseprint(isinstance(d, Base))
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 example to show working of multiple # inheritanceclass 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()
Base1
Base2
Derived
('Geek1', 'Geek2')

 
How to access parent members in a subclass?
Using Parent class name# Python example to show that base# class members can be accessed in# derived class using base class nameclass 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 Coded = Derived(10, 20)d.printXY()Output:(10, 20)
Using super()We can also access parent class members using super.# 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 Coded = Derived(10, 20)d.printXY()Output:(10, 20)
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   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)Output:4
8
24
# Base or Super classclass 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 codeemp = Employee("Geek1", "E101") print(emp.getName(), emp.isEmployee(), emp.getID())Output:('Geek1', True, 'E101')
YouTubeGeeksforGeeks500K subscribersPython Programming Tutorial | Object Oriented Programming in Python - Part 3 | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gypMW9KJwok" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Shwetanshu Rohatgi and Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveMy Personal Notes
arrow_drop_upSave
Using Parent class name# Python example to show that base# class members can be accessed in# derived class using base class nameclass 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 Coded = Derived(10, 20)d.printXY()Output:(10, 20)

# Python example to show that base# class members can be accessed in# derived class using base class nameclass 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 Coded = Derived(10, 20)d.printXY()
(10, 20)

Using super()We can also access parent class members using super.# 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 Coded = Derived(10, 20)d.printXY()Output:(10, 20)
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   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)Output:4
8
24
# Base or Super classclass 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 codeemp = Employee("Geek1", "E101") print(emp.getName(), emp.isEmployee(), emp.getID())Output:('Geek1', True, 'E101')
YouTubeGeeksforGeeks500K subscribersPython Programming Tutorial | Object Oriented Programming in Python - Part 3 | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gypMW9KJwok" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Shwetanshu Rohatgi and Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveMy Personal Notes
arrow_drop_upSave
# 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 Coded = Derived(10, 20)d.printXY()
(10, 20)

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
   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)Output:4
8
24
# Base or Super classclass 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 codeemp = Employee("Geek1", "E101") print(emp.getName(), emp.isEmployee(), emp.getID())Output:('Geek1', True, 'E101')

   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)Output:4
8
24

   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)
4
8
24

# Base or Super classclass 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 codeemp = Employee("Geek1", "E101") print(emp.getName(), emp.isEmployee(), emp.getID())Output:('Geek1', True, 'E101')

# Base or Super classclass 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 codeemp = Employee("Geek1", "E101") print(emp.getName(), emp.isEmployee(), emp.getID())
('Geek1', True, 'E101')

YouTubeGeeksforGeeks500K subscribersPython Programming Tutorial | Object Oriented Programming in Python - Part 3 | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gypMW9KJwok" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Shwetanshu Rohatgi and Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Ani_1107
fridayda13
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
C++ Classes and Objects