1. About Inheritance In OOP Python

To avoid copying the code of a class, we use the inheritance method. The inheritance method consists in creating from a parent class another class called a child class which inherits all the methods and properties of the parent class.

2. How To Us The Inheritance In OOP Python

To simplify the acquisition for beginner learners, we will treat this concept on a simple example:

Parent class:

class Person:
     def __init__(self,name,age):
         self.name = name
         self.age=age

We have just defined a Person class whose attributes are name and age. We are now going to create a child class named Student which inherits the same methods and properties from the parent class Person. The general syntax of inheritance is done using the command:

class child_class(mother_class)

Which means that the class child_class inherits from the class class_mother.
In our case, the Student child class inherits from the Person parent class.

Example ( Student inherits from class Person)

class Student(Person):

The inheritance of the name and age attributes is done via the command:

Person.__init__(self,name,age)

Student child class code:

class Student(Person):
    # definition of attributes of attributes
    def __init__(self,name,age,field):
        # inheritance of attributes from parent class Person
        Person.__init__(self,name,age)
        # add a new attribute filiere to the child class
        self.file = file

Complete example

# define parent class Person
class Person:
     def __init__(self,name,age):
         self.name = name
         self.age=age
# The Student child class inherits from the Person parent class
class Student(Person):
    # definition of attributes of attributes
    def __init__(self,name,age,section):
        # inheritance of attributes from parent class Person
        Person.__init__(self,name,age)
        # add a new attribute section to the child class
        self.section = section
Stud = Student("Albert",27,"math")
print("The student's name is: ",Stud.name)
print("The age of the student is: ",Stud.age)
print("The student's section is: ",Stud.section)
"""
Which displays after execution:
The student's name is: Albert
The age of the student is: 27
The student's section is: math
"""

3. Multiple inheritance

In object-oriented programming, we speak of multiple inheritance, when a class inherits from two or more classes.

Example (multiple inheritance)

class Compute1:  
    def sum(self,a,b):  
        return a + b 
    
class Compute2:  
    def Multiplication(self,a,b):  
        return a*b

# multiple inheritance  
class Compute3(Compute1,Compute2):  
    def division(self,a,b):  
        return a/b 
    
Compute = Compute3()  
print(Compute.sum(7 , 5)) # display 12 
print(Compute.Multiplication(10 , 5)) # display 50 
print(Compute.division(8 , 3))  # display 2.666666

 

Younes Derfoufi
my-courses.net

Leave a Reply