Basic Inheritance & Hierarchy
Inheritance is a fundamental pillar of Object-Oriented Programming that allows you to create new classes based on existing ones. It facilitates code reuse by allowing a Subclass (Child) to inherit the attributes and behaviors of a Base Class (Parent).
In Python, inheritance is not just about copying code; it’s about establishing a logical hierarchy where specialized objects can leverage and extend the functionality of more general ones.
1. The “is-a” Relationship
Section titled “1. The “is-a” Relationship”Inheritance should only be used when there is a clear “is-a” relationship between the two entities.
- A
Manageris aEmployee. - A
Circleis aShape. - A
Smartphoneis aDevice.
class Employee: def __init__(self, name, salary): self.name = name self.salary = salary
def get_details(self): return f"{self.name} earns ${self.salary}"
# Manager inherits from Employeeclass Manager(Employee): def plan_meeting(self): print(f"{self.name} is planning a meeting.")
m = Manager("Alice", 90000)print(m.get_details()) # Inherited from Employee2. Extending Logic with super()
Section titled “2. Extending Logic with super()”Often, you don’t want to completely replace a parent’s method; you want to run the parent’s logic and then add your own. The super() function allows you to call methods from the parent class without explicitly naming it.
class Manager(Employee): def __init__(self, name, salary, department): # Let the parent class handle name and salary super().__init__(name, salary) # Add the manager-specific attribute self.department = department
def get_details(self): # Call the parent's version and append more info basic_info = super().get_details() return f"{basic_info} and manages {self.department}"3. Introspection: isinstance and issubclass
Section titled “3. Introspection: isinstance and issubclass”Because of inheritance, an object can be an instance of multiple classes.
m = Manager("Alice", 90000, "HR")
print(isinstance(m, Manager)) # Trueprint(isinstance(m, Employee)) # True (Because Manager is an Employee)print(isinstance(m, object)) # True (Everything is an object in Python)
print(issubclass(Manager, Employee)) # True4. Under the Hood: The __bases__ Attribute
Section titled “4. Under the Hood: The __bases__ Attribute”How does Python know which class is the parent? Every class has a hidden attribute called __bases__ that stores a tuple of its parent classes.
print(Manager.__bases__)# Output: (<class '__main__.Employee'>,)When you call a method like m.get_details(), Python first looks in the Manager class. If it’s not there, it checks the classes listed in __bases__.
5. Summary Table
Section titled “5. Summary Table”| Term | Meaning |
|---|---|
| Base Class | The parent class being inherited from. |
| Subclass | The child class that is inheriting. |
| Overriding | Replacing a parent’s method with a child’s version. |
| Extending | Using super() to build upon a parent’s method. |
| Object | The root of all classes in Python 3. |