OOP in Python: Inheritance

  • Inheritance allows us to define a class that inherits all the methods and properties from another class
  • Parent class is the class being inherited from, also called base class
  • Child class is the class that inherits from another class, also called derived class
  • Any class can be a parent class, so the syntax is the same as creating any other class:

Example:

Create a class named Person, with firstname and lastname properties, and a printname method:

class Person:
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname

    def printname(self): # printname method
        print(self.fname, self.lname)
        
#Use the Person class to create an object, and then execute the printname method:
p1 = Person('Chucknorris', 'Madamombe')
p1.printname()

 

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:

class Student(Person):
    pass

 

Add the __init__() Function

  • So far we have created a child class that inherits the properties and methods from its parent.
  • We want to add the __init__() function to the child class
  • Note: The __init__() function is called automatically every time the class is being used to create a new object.
class Student(Person):
# When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.
  def __init__(self, fname, lname):
    #add properties etc.
  • Note: The child’s __init__() function overrides the inheritance of the parent’s __init__() function.
  • To keep the inheritance of the parent’s __init__() function, add a call to the parent’s __init__() function:
class Student(Person):
  def __init__(self, fname, lname):
    Person.__init__(self, fname, lname)

Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__() function.

 

Use the super() Function

  • Python also has a super() function that will make the child class inherit all the methods and properties from its parent:
  • By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.
class Student(Person):
  def __init__(self, fname, lname, year):
    super().__init__(fname, lname)
    self.graduationyear = year

  def welcome(self): # If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.
    print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
# create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
    def __init__(self, firstname, lastname, age, graduationyear, email): # define the __init__() function and add aditional properties
        super().__init__(firstname, lastname, age) #use super().__init__() function of the parent class
        self.graduationyear = graduationyear
        self.email = email
    def welcome(self):
        welcome_message = print('My name is ' + self.firstname + ' ' + self.lastname + '. ' + 'I am ' + str(self.age) + ' years old.'
                                + 'I attended my first graduation in the year ' + str(self.graduationyear) + '.' + ' My email address is ' + self.email + '.' 
                                )
#create objects from the Student class, and call the welcome method.
s = Student('Chucknorris', 'Madamombe', 35, 2012, '[email protected]')
s.welcome()

 

Python Inheritance Example

  • ‘e1’ is the instance created for the class Employee.
  • It invokes the __init__() of the referred class.
  • You can see ‘object’ written in the declaration of the class Person.
  • In Python, every class inherits from a built-in basic class called ‘object’.
  • The constructor i.e. the ‘__init__’ function of a class is invoked when we create an object variable or an instance of the class.
  • The variables defined within __init__() are called as the instance variables or objects.
  • Hence, ‘name’ and ‘idnumber’ are the objects of the class Person.
  • Similarly, ‘salary’ and ‘post’ are the objects of the class Employee.
  • Since the class Employee inherits from class Person, ‘name’ and ‘idnumber’ are also the objects of class Employee.
  • If you forget to invoke the __init__() of the parent class then its instance variables would not be available to the child class.
# Python code to demonstrate how parent constructors
# are called
# parent class
class Person(object):   

        # __init__ is known as the constructor        
        def __init__(self, name, idnumber):  
                self.name = name
                self.idnumber = idnumber

        def display(self):
                print(self.name)
                print(self.idnumber)
 
# child class
class Employee(Person):          
        def __init__(self, name, idnumber, salary, post):
                self.salary = salary
                self.post = post
 
                # invoking the __init__ of the parent class
                super().__init__(name, idnumber)
 
        def income(self):
            print(self.name, self.idnumber, self.salary, self.post)   

# creation of an object variable or an instance 
e1 = Employee('Chuck', '1843107678h18', '$20 000', "Engineer")   

# calling a function of the class Person using its instance
e1.income()

Get full code from my GitHub repo. 

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *