Inheritance lets one class build on another, reusing its attributes and methods and adding or changing what it needs. It models "is-a" relationships: a Student is a Person, so it inherits everything a Person can do.
Subclassing & super()
A subclass lists its parent in parentheses. Call super() to reuse the parent's implementation:
class Person:def __init__(self, name):self.name = namedef greet(self):return f"Hi, I'm {self.name}"class Student(Person): # Student inherits from Persondef __init__(self, name, track):super().__init__(name) # run Person's constructor firstself.track = track # then add Student-specific statedef greet(self): # OVERRIDE the parent's methodreturn f"{super().greet()}, learning {self.track}"Student("Aanya", "Python").greet() # "Hi, I'm Aanya, learning Python"
Overriding & extending
A subclass can override a method (replace it entirely) or extend it (call super() then add to it, as above). Methods it doesn't override are inherited unchanged.
Prefer shallow hierarchies
Key takeaways
- 01Inheritance models "is-a": a subclass reuses a parent's attributes and methods.
- 02List the parent in parentheses: class Student(Person).
- 03super() calls the parent implementation (e.g. its __init__).
- 04A subclass can override a method or extend it via super().
- 05Keep hierarchies shallow; favour composition for "has-a" relationships.
