Inheritance is an Object-Oriented Programming (OOP) feature that allows one class to inherit properties and methods from another class.
The class being inherited from is called the Parent Class (Base Class), and the class that inherits is called the Child Class (Derived Class).
Basic Inheritance
Example
class Person:
def greet(self):
print("Hello")
class Student(Person):
pass
student = Student()
student.greet()
Output:
Hello
Inheriting Attributes
Example
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
pass
student = Student("John")
print(student.name)
Output:
John
Adding New Methods in Child Class
Example
class Person:
def greet(self):
print("Hello")
class Student(Person):
def study(self):
print("Studying")
student = Student()
student.greet()
student.study()
Output:
Hello
Studying
Method Overriding
A child class can provide its own implementation of a parent class method.
Example
class Person:
def greet(self):
print("Hello from Person")
class Student(Person):
def greet(self):
print("Hello from Student")
student = Student()
student.greet()
Output:
Hello from Student
Using super()
The super() function allows access to parent class methods.
Example
class Person:
def greet(self):
print("Hello from Person")
class Student(Person):
def greet(self):
super().greet()
print("Hello from Student")
student = Student()
student.greet()
Output:
Hello from Person
Hello from Student
Constructor Inheritance
Example
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
pass
student = Student("John")
print(student.name)
Output:
John
Calling Parent Constructor with super()
Example
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, age):
super().__init__(name)
self.age = age
student = Student("John", 20)
print(student.name)
print(student.age)
Output:
John
20
Multiple Inheritance
A class can inherit from multiple parent classes.
Example
class Father:
def father_skill(self):
print("Driving")
class Mother:
def mother_skill(self):
print("Cooking")
class Child(Father, Mother):
pass
child = Child()
child.father_skill()
child.mother_skill()
Output:
Driving
Cooking
Summary
- Inheritance allows a class to reuse code from another class.
- The parent class provides attributes and methods.
- The child class inherits those attributes and methods.
- Child classes can add new methods.
- Method overriding allows redefining parent methods.
super()is used to access parent class methods and constructors.- Python supports multiple inheritance.