Docsity

Python slides powerpoint, Slides of Computer science

Partial preview of the text

Download Python slides powerpoint and more Slides Computer science in PDF only on Docsity!

Python

Day 2: Inheritance & Polymorphism

inherits · super() · MRO · isinstance · issubclass · method overriding · duck typing

Python OOP: Level 2

The Journey: What You're Building TODAY — Inheritance & Polymorphism

Extend existing classes with inheritance and write polymorphic code.

Day 1

Classes &

Objects

Day 2

Inheritance &

Polymorphism

Day 3

Encapsulation

& Dunders

Day 4

Modules &

Packages

Day 5

Unit Testing

& pytest

Day 6

Git &

GitHub

Day 7

OOP

Design

Day 8

Comprehensions

& Generators

Day 9

Advanced

OOP

Day 10

Final

Project

Why this matters:

Inheritance models IS-A relationships: ElectricCar IS-A Car

Polymorphism lets different objects share an interface — same method, different behavior

Python's MRO determines which parent method is called in complex hierarchies

Inheritance — Extending Classes

A subclass inherits all methods and attributes from its parent. Use super() to call the parent's version.

(continued)

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):

EXTEND — call parent then add more

parent_result = super().start() return parent_result + ", seatbelt reminder!" class Truck(Vehicle): def start(self):

REPLACE — completely new behavior

return "Diesel truck cranking up..." c = Car(); t = Truck() print(c.start()) # Engine started, seatbelt reminder! print(t.start()) # Diesel truck cranking up...

Method Overriding Extending vs Replacing Parent Methods

isinstance(), issubclass() & the MRO

isinstance() is the right way to check types. The MRO determines method resolution order in complex

hierarchies.

class Animal: pass class Dog(Animal): pass class Cat(Animal): pass rex = Dog()

isinstance: is this object an instance of that

class (or subclass)? print(isinstance(rex, Dog)) # True print(isinstance(rex, Animal)) # True — Dog IS-A Animal print(isinstance(rex, Cat)) # False

issubclass: is this class a subclass of another?

print(issubclass(Dog, Animal)) # True print(issubclass(Dog, Dog)) # True — itself! print(issubclass(Animal, Dog)) # False

isinstance() is the right way to type-check:

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

Polymorphic function — works with ANY shape:

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...

isinstance() and issubclass()

Polymorphism — Same Interface, Different

Behavior

Abstract Base Classes & Interfaces

ABCs enforce that subclasses implement required methods — Python's way of defining 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.

With ABC:

from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass # MUST be overridden class BadShape(Shape): pass

BadShape() ← TypeError: Can't instantiate

abstract

class BadShape with abstract method

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}")

The Problem ABCs Solve Defining an Abstract Base Class

Abstract Base Classes & Interfaces

ABCs enforce that subclasses implement required methods — Python's way of defining interfaces.

(continued)

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)

Now safe to call polymorphically:

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.

Implementing Abstract Classes @property — Computed Attributes

Exercises 3 & 4: Polymorphism & isinstance

Write polymorphic functions and check types correctly.

Exercise 3: Polymorphic shape area calculator

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}")

Exercise 4: isinstance guard

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

Enforce interfaces with ABC and expose computed values as properties.

from abc import ABC, abstractmethod

Exercise 5: Abstract Vehicle base class

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

Build a game character hierarchy using inheritance, ABCs, and polymorphism.

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

Build a game character hierarchy using inheritance, ABCs, and polymorphism. (continued)

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

Inheritance

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

Polymorphism

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

MRO & Properties

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

Make sure to keep practising Python -- growth doesn't happen overnight!