image by mohamed_hassan pixabay

Python Inheritance allows one to define a class that will be able to inherit all the methods and properties from another class. There is the Parent class or Base class, which is the class being inherited from. Then there is the Child class or Derived class, which is the class that inherits from another class.

Creating the Parent Class

Any class can be a Parent class. The syntax of the Parent class is the same as creating any other class. For example:

Let us create a class named Teacher, containing the firstname and the lastname properties and also contains the method printname. This is how you create it below:

class Teacher:  #create the class and name it Teacher, the parent class
    def __init__(self, fname, lname): #create a function
        self.firstname = fname
        self.lastname = lname

    def printname(self): #create a method using printname
        print(self.firstname, self.lastname)

x = Teache("Ann", "Smith") #assign a variable
x.printname()  #call the function

Creating the Child Class

Creating the Child class it will inherit the functionality from another class. You can make the Parent class as the parameter when creating the Child class. For example:

Let us create a child class called Student. The child class will inherit the properties and the methods from the class named Teacher. This is how you create it:

class Student(Teacher):
    pass # used when you do not want to add
         # any properties or methods to the class


# This is used when you want to add an object
# and then execute the printname method

class Student(Teacher):
    x = Student("Ann", "Smith")

Next we will learn how to add properties, functions, (that is the super() and the __init__ functions), and the methods to the Python inheritance code.

If you have any question or comment, do not hesitate to ask us.

Quote: The moon looks upon many night flowers; the night flowers see but one moon. – Jean Ingelow