In this tutorial we are going to learn :
- Inheritance in Python
- Method Overriding
- Multiple Inheritance
Inheritance in Python
If we have more than one class and we want to access all the methods and properties from another class then we can use inheritance.
Parent class : is the class being inherited from.
Child class : is the class that inherits from another class.
Let’s explain something :
- Cat and Bird both eat. Instead of creating eat() methods for each one of them, we create one time in Animal class and we inherit from Animal class.
class Animals: def eat(self): print("eat") class Cat(Animals): # inheritance from Animals class def walk(self): print("walk") class Bird(Animals): def fly(self): print("fly") cat = Cat() cat.eat() cat.walk()
Child class can only access methods and variables from inside the class. Method overriding allows child class to access parent class variables from outside.
- We use the super() method to method override.
As you can see, child class can access parent class variables.
# Parent Class class Person: def __init__(self): self.name = "James" # Child Class class Student(Person): def __init__(self): super().__init__() # Method Overriding self.age = 21 student = Student() print(student.name) print(student.age)
We can also inherit from multiple classes.
In this program, you have to be careful about the method name. If we inherit from multiple classes and they have methods with the same name, the child class will inherit the first class here. As you can see first class is Student here so Human class inherits from Student class first.
class Student: def my_method(self): print("Student") class Teacher: def my_method(self): print("Teacher") class Human(Student, Teacher): pass human = Human() human.my_method()