Python ยท Chapter 29 of 45
Python Inheritance
A subclass INHERITS attributes and methods from its parent. Declare with `class Child(Parent):`.
Use `super().__init__(...)` to call the parent constructor.
Overriding methods
A subclass can redefine any parent method. Call `super().method()` to reuse the parent's implementation.
Multiple inheritance
Python supports it: `class C(A, B):`. Method resolution follows the MRO (method resolution order).
Example 1 (python)
class Animal:
def speak(self):
return "some sound"
class Cat(Animal):
def speak(self):
return "meow"
print(Cat().speak())Output
meowCat overrides speak().
Example 2 (python)
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, roll):
super().__init__(name)
self.roll = roll
s = Student("Ana", 21)
print(s.name, s.roll)Output
Ana 21Student extends Person and adds a roll attribute.
Key points
- `class Child(Parent):` inherits.
- `super()` refers to the parent class.
- Subclasses can override methods.
- Prefer composition over deep inheritance chains.
๐ก Note: Use `isinstance(obj, Parent)` to check if an object is any subclass of Parent.
