Object-Oriented Programming
Introduction to OOP
Object-Oriented Programming (OOP) allows you to model real-world entities. It increases modularity, reusability, and abstraction. Instead of just functions, you organize code into 'Classes' (blueprints) and 'Objects' (instances).
Python# Functional approach def bark(): print("Woof!") # OOP approach class Dog: def bark(self): print("Woof!") d = Dog() d.bark()
Classes & Objects
A Class is a blueprint defining attributes and behaviors. An Object is a specific instance of that class. The `__init__` method (constructor) initializes new objects.
Pythonclass Car: def __init__(self, brand, model): self.brand = brand # Attribute self.model = model def drive(self): # Method print(f"{self.brand} {self.model} is driving") my_car = Car("Tesla", "Model S") my_car.drive()
Instantiation Flow
__init__ runs?
Encapsulation
Encapsulation bundles data and methods, restricting direct access to some of an object's components. In Python, use `_` for protected and `__` for private attributes (convention).
Pythonclass Account: def __init__(self, balance): self.__balance = balance # Private def deposit(self, amount): if amount > 0: self.__balance += amount acc = Account(100) # print(acc.__balance) # Error! Private. acc.deposit(50) # Safe access via method
Inheritance
Inheritance allows a class (Child) to derive attributes and methods from another (Parent). This promotes code reuse. The child can override methods to change behavior.
Pythonclass Animal: def speak(self): print("Some sound") class Dog(Animal): def speak(self): print("Woof!") d = Dog() d.speak() # "Woof!" (Child overrides Parent)
Inheritance Tree
Parent: Animal
Polymorphism
Polymorphism means 'many forms'. Different classes can share the same method name but have different implementations. This allows you to treat objects uniformly.
Pythonanimals = [Dog(), Cat()] for animal in animals: animal.speak() # "Woof!" then "Meow!"
Polymorphism
animal.speak()
Abstraction
Abstraction hides complex implementation details and shows only the necessary features using Abstract Base Classes (ABCs). An abstract method MUST be implemented by subclasses.
Pythonfrom abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def __init__(self, r): self.r = r def area(self): return 3.14 * self.r ** 2 # s = Shape() # Error! Cannot instantiate abstract class
Special Methods (Magic Methods)
Special methods start and end with double underscores (`__`). They let you define how objects behave with operators like +, -, len(), and print().
Pythonclass Vector: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"({self.x}, {self.y})" def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) v1 = Vector(1, 2) v2 = Vector(3, 4) print(v1 + v2) # Output: (4, 6)
Real-World: Bank Account
Putting it all together: A bank system with secure (encapsulated) balances and different account types (inheritance).
Pythonclass BankAccount: def __init__(self, owner, balance): self.owner = owner self.__balance = balance def deposit(self, amount): self.__balance += amount def get_balance(self): return self.__balance class Savings(BankAccount): def add_interest(self): interest = self.get_balance() * 0.05 self.deposit(interest)
Master this concept
Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.
Visual Lab
Class to Object
Class Car (Blueprint)
New Challenge available!
Master Object-Oriented Programming with a hands-on task.