









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










The Journey: What You're Building TODAY — Inheritance & Polymorphism
Day 1
Day 2
Day 3
Day 4
Day 5
Day 6
Day 7
Day 8
Day 9
Day 10
Why this matters:
Inheritance — Extending Classes
class Shape: def area(self): return 0 # default — should be overridden def describe(self): return f"Shape with area {self.area():.2f}" class Circle(Shape): def init(self, radius): self.radius = radius def area(self): # OVERRIDES Shape.area() import math return math.pi * self.radius ** 2 class Square(Shape): def init(self, side): self.side = side def area(self): # OVERRIDES Shape.area() return self.side ** 2 class Vehicle: def start(self): return "Engine started" def info(self): return f"Vehicle: {type(self).name}" class Car(Vehicle): def start(self):
parent_result = super().start() return parent_result + ", seatbelt reminder!" class Truck(Vehicle): def start(self):
return "Diesel truck cranking up..." c = Car(); t = Truck() print(c.start()) # Engine started, seatbelt reminder! print(t.start()) # Diesel truck cranking up...
isinstance(), issubclass() & the MRO
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass rex = Dog()
class (or subclass)? print(isinstance(rex, Dog)) # True print(isinstance(rex, Animal)) # True — Dog IS-A Animal print(isinstance(rex, Cat)) # False
print(issubclass(Dog, Animal)) # True print(issubclass(Dog, Dog)) # True — itself! print(issubclass(Animal, Dog)) # False
def process(animal): if isinstance(animal, Dog): print("It's a dog — fetch!") class Circle: def init(self, r): self.r = r def area(self): return 3.14159 * self.r** class Rectangle: def init(self, w, h): self.w=w; self.h=h def area(self): return self.w * self.h class Triangle: def init(self, b, h): self.b=b; self.h=h def area(self): return 0.5 * self.b * self.h
def total_area(shapes): return sum(s.area() for s in shapes) shapes = [Circle(5), Rectangle(3,4), Triangle(6,2)] print(total_area(shapes)) # 84.54...
Abstract Base Classes & Interfaces
class Shape: def area(self): pass # ← what happens if a subclass forgets? class BadShape(Shape): pass # ← forgot to implement area()! s = BadShape() print(s.area()) # None — no error! Silent bug.
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass # MUST be overridden class BadShape(Shape): pass
abstract
area from abc import ABC, abstractmethod import math class Shape(ABC): @abstractmethod def area(self) -> float: """Return the area of the shape.""" @abstractmethod def perimeter(self) -> float: """Return the perimeter of the shape.""" def describe(self): # concrete method — inheritable return (f"{type(self).name}: " f"area={self.area():.2f}, " f"perimeter={self.perimeter():.2f}")
Abstract Base Classes & Interfaces
from abc import ABC, abstractmethod import math class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Circle(Shape): def init(self, r): self.r = r def area(self): return math.pi * self.r** def perimeter(self): return 2 * math.pi * self.r class Rectangle(Shape): def init(self, w, h): self.w=w; self.h=h def area(self): return self.w * self.h def perimeter(self): return 2*(self.w+self.h)
for s in [Circle(5), Rectangle(3,4)]: print(s.describe()) class Temperature: def init(self, celsius): self._celsius = celsius # _ = private by convention @property def celsius(self): # getter return self._celsius @celsius.setter def celsius(self, value): # setter with validation if value < -273.15: raise ValueError("Below absolute zero!") self._celsius = value @property def fahrenheit(self): # read-only computed property return self._celsius * 9/5 + 32 t = Temperature(100) print(t.fahrenheit) # 212.0 — accessed like an attribute t.celsius = 0 # calls setter print(t.fahrenheit) # 32.
Exercises 3 & 4: Polymorphism & isinstance
class Circle: def init(self, r): self.r = r def area(self): import math; return math.piself.r* class Rectangle: def init(self, w, h): self.w=w; self.h=h def area(self): return self.wself.h class Triangle: def init(self, b, h): self.b=b; self.h=h def area(self): return 0.5self.b*self.h def describe_shapes(shapes): for s in shapes: name = type(s).___ # class name as string print(f"{name:12} area={s.area():.2f}") shapes = [Circle(3), Rectangle(4,5), Triangle(6,4)] describe_shapes(shapes) total = sum(s.___ for s in shapes) # call area() on each print(f"Total area: {total:.2f}")
def area_of(shape): if not isinstance(shape, (Circle,Rectangle,Triangle)): raise TypeError(f"Unknown shape: {type(shape).name}") return shape.area() print(area_of(Circle(1))) try: area_of("not a shape") except TypeError as e: print(e) type(s).name Returns the class name as a string: 'Circle', 'Rectangle', etc. s.area() polymorphism Python calls the correct area() based on the ACTUAL type of s at runtime. isinstance(s, (A,B,C)) Pass a tuple of types to isinstance() to check against multiple types at once. sum(s.area() for s in shapes) Generator expression calling area() on each — polymorphism in action.
Exercises 5 & 6: ABC & @property
from abc import ABC, abstractmethod
class Vehicle(ABC): def init(self, make, year): self.make = make; self.year = year @___ def fuel_cost_per_km(self) -> float: """Return cost per km in cents.""" def trip_cost(self, km): return self.fuel_cost_per_km() * km class Petrol(Vehicle): def fuel_cost_per_km(self): return 12.5 # 12.5 cents/km class Electric(Vehicle): def fuel_cost_per_km(self): return 3.2 # much cheaper @abstractmethod Decorator that marks a method as required. Subclasses MUST override it. fuel_cost_per_km() trip_cost calls self.fuel_cost_per_km() — polymorphism picks the right subclass version. @property + @x.setter @property creates a getter; @celsius.setter creates a setter with validation. self._c private attr The _ prefix is a convention for 'internal use'. The property exposes it cleanly.
Challenge: RPG Character System
from abc import ABC, abstractmethod class Character(ABC): def init(self, name, hp, atk): self.name = name; self.hp = hp; self.atk = atk @abstractmethod def special_move(self) -> str: ... def attack(self, target): damage = self.atk target.hp -= damage return f"{self.name} attacks {target.name} for {damage} dmg!" def is_alive(self): return self.hp > 0 def repr(self): return f"{type(self).name}({self.name!r}, hp={self.hp})" @abstractmethod special_move Forces every subclass (Warrior, Mage) to define their own special move. attack modifies target.hp Python passes objects by reference — modifying target.hp changes the original object. type(self).name Returns 'Warrior' or 'Mage' — useful for flexible repr in base class.
Challenge: RPG Character System
class Warrior(Character): def init(self, name): super().init(name, hp=120, atk=25) def special_move(self): return f"{self.name} Shield Bash!" class Mage(Character): def init(self, name): super().init(name, hp=80, atk=40) def special_move(self): return f"{self.name} Fireball! 🔥" def battle(c1, c2): """Simple turn-based battle. Returns winner.""" while c1.is_alive() and c2.is_alive(): print(c1.attack(c2)) if c2.is_alive(): print(c2.attack(c1)) return c1 if c1.is_alive() else c @abstractmethod special_move Forces every subclass (Warrior, Mage) to define their own special move. attack modifies target.hp Python passes objects by reference — modifying target.hp changes the original object. type(self).name Returns 'Warrior' or 'Mage' — useful for flexible repr in base class.
Day Cheat Sheet
class Sub(Base): Sub inherits everything from Base super().init(...) call parent constructor super().method() call parent's version of method def method(self): override — replaces parent's isinstance(obj, Class) True if obj is that class/subclass issubclass(Sub, Base) True if Sub inherits from Base
Duck typing just call the method — no type check needed same interface, diff impl Circle.area() vs Rectangle.area() type(obj).name get class name as string from abc import ABC,abstractmethod enforce interface @abstractmethod must override in subclass
D.mro shows method resolution order C3 linearization Python's diamond-safe MRO algorithm @property getter — access like attribute @prop.setter setter with validation self._x convention underscore = internal/private
Day 2 Complete! Here's what you can now do: Use class inheritance to share code and model IS-A relationships Call super().init() to extend parent constructors without replacing them Override methods in subclasses for polymorphic behavior Check types safely with isinstance() and issubclass() Enforce interfaces with ABC and @abstractmethod; create computed attributes with @property