20.1 Programming Paradigms

Bulk view disabled for Guests. View lessons individually.

Object-Oriented Programming (OOP)

1. Classes & Objects

A Class is a blueprint. An Object is an instance of that blueprint.

class Student: def __init__(self, name, id): # Constructor self.name = name # Attribute self.id = id # Creating an object (Instantiating) student1 = Student("Nanjala", 101)

2. Encapsulation (Information Hiding)

Restricting access to data. In Python, we use a double underscore __ to make attributes Private. We then use Getters and Setters.

class Account: def __init__(self, balance): self.__balance = balance # Private attribute def get_balance(self): # Getter return self.__balance

3. Inheritance & Overriding

A child class "inherits" all methods from a parent class. Overriding happens when the child changes a parent method.

class User: # Parent def login(self): print("Logging in...") class Admin(User): # Child def login(self): # Overriding print("Admin logging in with extra security...")

4. Containment (Aggregation/Composition)

This describes a "Has-a" relationship. One class contains an object of another class as an attribute.

class Engine: def start(self): pass class Car: def __init__(self): self.my_engine = Engine() # Car CONTAINs an Engine

5. Overloading (Static Polymorphism)

Defining multiple methods with the same name but different parameters.
Note: Python does not support standard overloading natively like Java, but we simulate it with default arguments.

def add(a, b, c = 0): return a + b + c print(add(5, 5)) # Uses 2 params print(add(5, 5, 5)) # Uses 3 params
⚠️ Exam Note: Why use OOP?

Key points for Paper 3/4: Code Reusability (via Inheritance), Maintainability (Modular design), and Security (via Encapsulation). In your blockchain project, you'd likely have a Vote object and a User object interacting!