Python Inheritance
Inheritance lets us create a new class that automatically has access to all the methods and attributes of another class.
The superclass (or base class) is the original class being inherited from.
The subclass (or derived class) is the new class that inherits functionality from the superclass.
Defining a Superclass
Any regular class can act as a superclass. The syntax is the same as defining a normal class.
Example: Define a Person class
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def display_name(self):
print(self.first_name, self.last_name)
# Create an instance of Person
person1 = Person("Alice", "Smith")
person1.display_name()
Creating a Subclass
To create a subclass that inherits from a superclass, include the parent class in parentheses when defining the new class:
Example: Define a Student class
class Student(Person):
pass # No additional methods or attributes added
pass if you don’t want to add any extra functionality to the subclass.
Using the Subclass
student1 = Student("Bob", "Johnson")
student1.display_name()
The Student subclass now has all the attributes and methods of the Person superclass.
Python Inheritance: Adding Extra Property to Subclass
We can extend a subclass to include additional properties or methods instead of using pass. Here’s an example:
Python Code Example
# Parent class (Superclass)
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def display_name(self):
print(self.first_name, self.last_name)
# Subclass with an extra property
class Student(Person):
def __init__(self, first_name, last_name, student_id):
super().__init__(first_name, last_name) # Call parent constructor
self.student_id = student_id # New property
def display_student_info(self):
print(f"{self.first_name} {self.last_name}, ID: {self.student_id}")
# Create a Student object
student1 = Student("Bob", "Johnson", "S12345")
student1.display_name() # From parent class
student1.display_student_info() # From subclass
Key Points
- super().__init__(): Calls the parent class constructor to initialize inherited attributes.
- Extra property:
student_idis unique to the subclass. - Extra method:
display_student_info()is specific to the subclass and uses both inherited and new attributes.
Output
Bob Johnson Bob Johnson, ID: S12345
Difference from Using pass
Using pass → The subclass inherits everything but adds no new functionality.
Adding properties/methods → The subclass can extend or customize behavior while still inheriting from the parent class.