Introduction to Classes and Inheritance in Python

PythonServer Side ProgrammingProgramming

Object-oriented programming creates reusable patterns of code to prevent code redundancy in projects. One way that recyclable code is created is through inheritance, when one subclass leverages code from another base class.

Inheritance is when a class uses code written within another class.

Classes called child classes or subclasses inherit methods and variables from parent classes or base classes.

Because the Child subclass is inheriting from the Parent base class, the Child class can reuse the code of Parent, allowing the programmer to use fewer lines of code and decrease redundancy.

Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name −

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'


class Parent:        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"
   def parentMethod(self):
      print 'Calling parent method'
   def setAttr(self, attr):
      Parent.parentAttr = attr
   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
   def __init__(self):
      print "Calling child constructor"
   def childMethod(self):
      print 'Calling child method'
c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method


When the above code is executed, it produces the following result 

Calling child constructor
Calling child method
Calling parent method
Parent attribute :200
Published on 16-Jan-2018 17:41:42