Inheritance in Python

Inheritance in Python

Inheritance is a mechanism that allows us to create a new class - known as the child class - that is based on an existing class - the mother class, adding new attributes and methods in addition to the existing class. When you do this, the child class inherits attributes and methods from the parent class.

Inheritance really shines when you want to create classes that are very similar. All you have to do is write the code for the things they have in common in one class - the parent class. Then write code for very specific things in a different class - the child class. This saves you from duplicating the code.

Syntax :
                                class parent:
                                    # Body of parent class
                                
                                class child(parent):
                                    # Body of child class
                            
Notes ! Like the Java object class, in Python (from version 3.x), object is the parent of all classes.
"class parent(object)" and "class parent" are identical.

Simple inheritance

We have a class called Person defined as follows.

                                class Person(object):     
                                      
                                    # class constructor         
                                    def __init__(self, name, cin):    
                                        self.name = name 
                                        self.cin = cin 

                                    def show(self): 
                                        print("Name : ",self.name) 
                                        print("CIN : ",self.cin) 
                                

                                # creation of an instance variable
                                p=Person("ISMAIL", "EE456788")
        
                                # Call a function of the Person class using its instance
                                p.show()
                            

This class has attributes to store the identifier of a person (cin) and the name of each person (name).
and also this class has a show() method to display information about a person

‘P’ is the instance created for the Person class. It invokes __init__() from the parent class. You can see "object" written in the declaration of the Person class. In Python, each class inherits an integrated base class called "object". The constructor, that is, the ‘__init__’ function of a class is called when we create an object variable or an instance of the class.

An employee is a person, so We can therefore create a class called Employee that inherits from Person. This makes all the attributes available in the Person class readily available in Employee. We do not need to redefine them (possibility of reusing the code). The Employee class is defined as follows.

                                class Employee( Person ): 

                                    def __init__(self, name, cin, salary): 
                                        # Call __init__ of parent class (Person) 
                                        super().__init__(self, nom, cin) 

                                        self.salary = salary 

                            

However, the Employee class has a new attribute "salary" to store an employee's salary.

Example 1 :
                                class Person(object):     
                                      
                                    # Constructeur         
                                    def __init__(self, name, cin):    
                                        self.name = name 
                                        self.cin = cin 

                                    def afficher(self): 
                                        print("Name : ",self.name) 
                                        print("CIN : ",self.cin) 


                                class Employee(Person): 

                                    def __init__(self, name, cin, salary): 
                                        self.salary = salary 
                                  
                                    # Call __init__ of parent class (Person) 
                                    Person.__init__(self, name, cin) 
                                
                                p=Employee("Ismail", "EE4567", 7000)
                                p.afficher()
                            
Name : Ismail
CIN : EE4567

If no attribute is found in the class, the search continues to the parent class. This is repeated recursively, if the parent class is itself derived from other classes.

In Python, we use the super () function to call the methods of the parent class.

Multiple inheritance

Python allows us to derive a class from several classes at the same time, this is called Multiple inheritance. Its general format is:

                                Class parent_1:
                                    # Body of parent 1 class
                                 
                                Class parent_2:
                                    # Body of parent 2 class
                                 
                                Class parent_3:
                                    # Body of parent 3 class
                                 
                                Class child(parent_1, parent_2, parent_3):
                                    # Body of child class
                            

The child class is derived from three classes parent_1, parent_2, parent_3. As a result, it will inherit the attributes and methods of the three classes.

Example 2 :
                                class Base(object): 
      
                                    # Constructor
                                    def __init__(self, name): 
                                        self.name = name 
                                  
                                    # Return the name
                                    def getName(self): 
                                        return self.name 
                                  
                                  
                                class Child(Base): 
                                      
                                    # Constructor
                                    def __init__(self, name, age): 
                                        Base.__init__(self, name) 
                                        self.age = age 
                                  
                                    # Return the age
                                    def getAge(self): 
                                        return self.age 
                                  
                                class GrandChild(Child): 
                                      
                                    # Constructor
                                    def __init__(self, name, age, address): 
                                        Child.__init__(self, name, age) 
                                        self.address = address 
                                  
                                    # Return the address
                                    def getAddress(self): 
                                        return self.address         
                                  
                                # Drive code
                                g = GrandChild("ISMAIL", 32, "Meknes")   
                                print(g.getName(), g.getAge(), g.getAddress()) 
                            
ISMAIL 32 Meknes

The base class - object

In Python, all classes inherit from the object class implicitly. This means that the following two class definitions are equivalent.

                                        class Person:
                                            pass
                                        # AND 
                                        class Person(object):
                                            pass
                                    

The object class provides special methods with two underscores at the beginning and at the end, inherited from all classes. Here are some important methods provided by the object class.

  • __new__()
  • __init__()
  • __str__()

The __new__() method creates the object. After creating the object, it calls the __init__() method to initialize the attributes of the object. Finally, it returns the newly created object to the calling program. Normally, we don't replace the __new__() method. However, if you want to significantly change the way an object is created, you must replace it.

The __str__() method is used to return a well-formatted string representation of the object. The object class version of the __str__() method returns a string containing the name of the class and its memory address in hexadecimal.

Example 3 :
                                    class Person(object):     
                                          
                                        # Constructor       
                                        def __init__(self, name, cin):    
                                            self.name = name 
                                            self.cin = cin
    
                                    p=Person("ISMAIL", "EE456788")
                                    print(p)
                                
< __main__.Person object at 0x10c287358>

Of course, it is not very useful. We can easily override this method by defining a method named __str__() in the Person class as follows.

Example 4 :
                                    class Person(object):     
                                          
                                        # Constructor       
                                        def __init__(self, name, cin):    
                                            self.name = name 
                                            self.cin = cin
                                        
                                        def __str__(self):
                                            return self.name
    
                                    p=Person("ISMAIL", "EE456788")
                                    print(p)
                                
ISMAIL

Built-in inheritance functions in Python

Two built-in functions, isinstance() and issubclass(), are used to check inheritance. Function isinstance() returns True if the object is an instance of the class or other classes derived from it. Each class in Python inherits the base class object.

Example 5 :
                                class Person(object):     
                                      
                                    # Constructor        
                                    def __init__(self, name, cin):    
                                        self.name = name 
                                        self.cin = cin 

                                    def afficher(self): 
                                        print("Name : ",self.name) 
                                        print("CIN : ",self.cin) 


                                class Employee( Person ): 

                                    def __init__(self, name, cin, salary): 
                                        self.salary = salary 
                                  
                                    # call __init__ from parent class (Person)
                                    Person.__init__(self, name, cin) 
                                
                                p=Employee("Ismail", "EE4567", 7000)
                                
                                if(isinstance(p, Employee)):
                                    print("p is an instance of the class Person ")


                                if(issubclass(Employee, Person)):
                                    print("Employee is a subclass of Person")
                            
p is an instance of the class Person
Employee is a subclass of Person

Share this course with your friends :

This course is written by M. ESSADDOUKI Mostafa

Many people realize their hearts desires late in life. Continue learning, never stop striving and keep your curiosity sharp, and you will never become too old to appreciate life.

0 Comment(s)

To leave a comment you must have an account Sign up, or Sign in