Inheritance In Python
Python Inheritance: Comprehensive Theory
Inheritance allows us to define a class that inherits all the methods and properties from another class.
1. Parent vs Child Class
- Parent class (Base class) is the class being inherited from.
- Child class (Derived class) is the class that inherits from another class.
2. Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Use the Person class to create an object:
x = Person("John", "Doe")
x.printname()
3. Create a Child Class
To create a child class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:
class Student(Person):
pass
Now the Student class has the same properties and methods as the Person class.
x = Student("Mike", "Olsen")
x.printname()
__init__()
If you add an __init__() function to the child class, the child class will no longer inherit the parent's __init__() function.
[!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)
super()
Python also has a super() function that will make the child class inherit all the methods and properties from its parent:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
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.
6. Adding Properties and Methods
You can add your own properties and methods to the child class to extend the parent's functionality.
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print(f"Welcome {self.firstname} {self.lastname} to the class of {self.graduationyear}")
x = Student("Tanis", "Kumar", 2024)
x.welcome()
7. Overriding Methods
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.
class Person:
def greet(self):
print("Hello from Person")
class Student(Person):
def greet(self):
print("Hello from Student")
s = Student()
s.greet() # Output: Hello from Student