+

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

We have discussed the following Python Object Oriented Programming Topics

This article introduces Inheritance.

One of the main advantages of object-oriented programming is reuse. Inheritance is one of the mechanisms to achieve the same. In inheritance, a class (usually called a superclass) is inherited by another class (usually called a subclass). The subclass adds some attributes to the superclass.

Below is a sample Python program that demonstrates how inheritance is implemented in Python.

  
# Python program to demonstrate inheritance

 
# Base or Super class. Mark the object in parentheses.
# (Typically, the object is the ancestor of all classes)
# В Python 3.x & quot; Person class & quot; yes
# equivalent to the & quot; Person class (object) & quot;

class Person ( object ):

 

# Constructor

def __ init __ ( self , name):

  self . name = name

 

# To get the 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 brackets)

class Employee (Person):

 

# We return true here

def isEmployee ( self ):

return True

 
# Driver code

emp = Person ( "Geek1" # Personality object

print (emp.getName (), emp.isEmployee ())

 

emp = Employee ( "Geek2" ) # Employee object

print (emp.getName (), emp.isEmployee ())

Output:

 (`Geek1`, False) (` Geek2`, True) 

How to check if a class is a subclass of another ?
Python provides the issubclass () function that tells us directly if a class is a 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 code

print ( issubclass (Derived, Base))

print ( issubclass (Base, Derived))

 

d = Derived ()

b = Base ()

 
# b is not a Derived instance

print ( isinstance (b, Derived))

  
# But d is a Base instance

print ( isinstance (d, Base))

Exit:

 True False False True 

What is an object class?
Like the Java Object class, in Python (since 3.x) the object is the root of all classes.

In Python 3.x " class Test (object) "and" class Test "are the same.
In Python 2.x, the “Test class (object)” creates a class with an object as a parent (called a new-style class), and “Test class” creates an old-style class (without an object parent). Refer to this for more details.

Does Python support multiple inheritance?
Unlike Java and C ++, Python supports multiple inheritance. We indicate all parent classes as a list separated by commas in brackets.

# Python example to show multiple work
# 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 Base1 constructors

# and Base2 classes

Base1 .__ init __ ( self )

Base2 .__ init __ ( self )

print "Derived"

 

def printStrs ( self ):

print ( self . str1, self . str2)

 

 

ob = Derived ( )

ob.printStrs ()

Exit:

 Base1 Base2 Derived (`Geek1`,` Geek2`) 

How to get access to parent members in the subclass?

  1. Using the parent class name

    # Python example, to show this base
    # class members can be accessed in
    # derived class using the base name class

    class Base ( object ):

     

    # Constructor

    def __ init __ ( self , x):

    self . x =

     

    class Derived (Base):

     

    # Constructor

    def __ init __ ( self , x, y) :

    Base.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 ()

    Output:

     (10, 20) 
  2. Using super ()
    We can also access the parent members of a class using super.

    # Python example to show this base
    # class members can be accessed in
    # derived class using super ()

    class Base ( object ):

     

      # Constructor

      def __ init __ ( self , x):

    self . x =

      

    class Derived (Base):

     

    # Constructor

    def __ init __ ( self , x, y):

     

    & # 39; & # 39; & # 39; In Python 3.x & quot; super () .__ init __ (name) & quot;

    also works & # 39; & # 39; & # 39;  

    super ( Derived, self ) .__ init __ (x)

    self . y = y

     

    def printXY ( self ):

     

    # Note that Base.x won`t work here

      # because super () used in constructor

    print ( self . x, self . y)

      

      
    Driver code

    d = Derived ( 10 , 20 )

    d.printXY ()

    Exit :

     (10, 20) 
  3. Please note that the above two methods are not exactly the same. In the next article on inheritance, we`ll cover the following topics.
    1) How does super work? What is the difference between accessing a member via super and parent class name?
    2) How is the diamond problem solved in Python?

    Exercise:
    Predict the output of the following Python programs

    1.  

      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)

      Exit :

       4 8 24 
    2. # 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 brackets)

      class Employee (Person):

        def __ init __ ( self , name, eid):

       

      & # 39; & # 39; & # 39; In Python 3.0+ & quot; super () .__ init __ (name) & quot;

      also works & # 39; & # 39; & # 39;  

      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 ())

      Exit:

       (`Geek1`, True,` E101`) 

    This article contributed by Shwetanshu Rohatgi and Mayank Rawat . If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

    Please post comments if you find anything wrong or if you`d like to share more information on the topic under discussion

Get Solution for free from DataCamp guru