Inheritance lets a new class (child) reuse and extend an existing class (parent).
class Dog(Animal): — Dog gets all of Animal's attributes and methods.
super()
Call the parent's method from the child, especially in __init__: super().__init__(name).
Overriding
A child can define a method with the same name to change its behaviour.
Polymorphism
Different classes share a method name, so the same code works with all of them: for shape in shapes: print(shape.area()).
Checking types
isinstance(obj, Animal) and issubclass(Dog, Animal).
Multiple inheritance
class C(A, B): — Python decides method order with the MRO (C.__mro__). Use it carefully; small mixin classes are a common, safe use.
Abstract classes
from abc import ABC, abstractmethod — a base class that cannot be created directly and forces children to implement certain methods.
Prefer composition (an object having another object) when "is-a" doesn't fit.
Example
from abc import ABC, abstractmethod
import math
class Shape(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def area(self) -> float: ...
def describe(self):
return f"{self.name} with area {self.area():.2f}"
class Rectangle(Shape):
def __init__(self, w, h):
super().__init__("Rectangle")
self.w, self.h = w, h
def area(self):
return self.w * self.h
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
self.name = "Square"
class Circle(Shape):
def __init__(self, r):
super().__init__("Circle")
self.r = r
def area(self):
return math.pi * self.r ** 2
for shape in [Rectangle(4, 5), Square(3), Circle(2)]:
print(shape.describe())
print(isinstance(Square(2), Rectangle))
Output: Rectangle with area 20.00, Square with area 9.00, Circle with area 12.57, True. Trying Shape("x") would raise TypeError because Shape is abstract.