๐งฑ What is Object Oriented Programming?
Object Oriented Programming (OOP) lets you model real-world things as objects โ bundles of data and behavior together. Instead of writing separate functions and variables, you group them into classes, which are blueprints for creating objects.
Why? Code reuse, clarity, and organization. A banking system doesn't need separate functions for every account type โ one BankAccount class handles them all.
๐๏ธ Four Pillars of OOP
๐ฆ The Business Scenario
SouthBank India's backend needs to handle thousands of accounts โ savings, checking, credit lines. Each behaves differently (interest rates, overdraft policies), but they share common traits (account holder, balance, deposit/withdraw). OOP lets you build one reusable BankAccount class, then specialize it via inheritance.
๐ป Step 1: Create a Basic BankAccount Class
Every class needs __init__ to initialize objects. The self parameter refers to the object itself. Instance attributes store data unique to each object.
๐ค Step 2: Add `__str__` & `__repr__` for Readability
__str__ returns a friendly string for users. __repr__ is a developer-friendly representation. Both help debugging and logging.
๐ Step 3: Inheritance โ SavingsAccount & CurrentAccount
Child classes inherit from a parent class. SavingsAccount adds interest; CurrentAccount allows overdraft. Both reuse deposit/withdraw from the parent.
โก Step 4: `super()` & Overriding Methods
super() calls the parent class's method. Overriding lets a child method replace the parent version. Here, CurrentAccount.withdraw() overrides the parent to allow negative balance.
๐ท๏ธ Step 5: Class Attributes vs Instance Attributes
Instance attributes are unique to each object (account number, balance). Class attributes are shared by all instances (bank name, interest rates). Modify class attributes carefully โ they affect all objects.
๐ Also Used In
OOP Across Every Domain
๐ค AI & Machine Learning Connection
Every machine learning framework (TensorFlow, PyTorch, scikit-learn) is built on OOP. A neural network is a Model class with train(), predict(), and evaluate() methods. When you inherit class MyModel(BaseModel), you're using the same inheritance pattern you're learning now โ but at scale with millions of parameters.
๐ฏ Mini Challenge
Create a Transaction class that models an M-Pesa transaction in Nairobi. Include instance attributes: phone_number, amount, recipient, status. Add a method confirm() that changes status to "completed" and prints a summary. Then create a child class LoanRepayment that inherits from Transaction and adds a loan_id attribute.
class Transaction: def __init__(self, phone, amount, recipient): self.phone_number = phone. Set self.status = "pending" by default. In confirm(), change status to "completed" and print details. For LoanRepayment, use super().__init__(...) and add self.loan_id in the child's __init__.
๐ค Interview Questions
self refers to the specific instance (object) that a method is called on. When you write acc.deposit(1000), inside the deposit method, self is acc. It lets you access that object's unique data: self.balance, self.account_holder, etc. Every method in a class takes self as the first parameter โ it's just a convention (you *could* name it something else, but don't).class BankAccount:. You create many objects from it: acc1 = BankAccount(...), acc2 = BankAccount(...). Each object has its own state โ acc1.balance and acc2.balance are independent.__init__) and shared by all instances. Example: bank_name = "SouthBank" โ every account object has the same bank_name. Instance attributes are defined in __init__ using self and are unique to each object. Example: self.balance โ each account has its own balance. Modifying a class attribute affects all instances; modifying an instance attribute affects only that object.class SavingsAccount(BankAccount): inherits all of BankAccount's methods. Why? Code reuse and specialization. Instead of rewriting deposit/withdraw for every account type, you write them once in BankAccount, then each child adds only what's different (interest for savings, overdraft for checking). This reduces bugs and makes maintenance easier.class Dog(Animal): if you only need a few methods, just pass an Animal object to Dog. Prefer shallow inheritance hierarchies โ deep ones get confusing fast.๐ง Quick Quiz
__init__ do in a Python class?acc1.withdraw(500), what does self refer to?super() do?__str__ return, and when is it called?๐ Quick Cheatsheet
| Concept | Syntax | Purpose |
|---|---|---|
class | class Name: | Define a class blueprint |
__init__ | def __init__(self, ...): | Initialize instance attributes |
self | self.attr = value | Reference current object |
Instance attr | self.balance = 1000 | Unique per object |
Class attr | bank_name = "SouthBank" | Shared by all instances |
Method | def deposit(self, amount): | Function inside a class |
Inheritance | class Child(Parent): | Inherit from parent class |
super() | super().__init__(...) | Call parent method |
__str__ | def __str__(self): | User-friendly string |
__repr__ | def __repr__(self): | Developer representation |
โ ๏ธ Common Mistakes
self in method definitionsself as the first parameter. def deposit(amount): will fail; use def deposit(self, amount):. Python passes the object automatically โ you just have to name it.__init__ with self. Define class attributes in the class body. If you modify a class attribute, all instances see the change. Beginners often accidentally create class attributes when they meant instance.super().__init__ in child classes__init__, call it via super().__init__(...) in the child. Otherwise, parent attributes won't be set up. This is a common source of silent bugs._attribute (one underscore) for "protected" and __attribute (two underscores) for "private" by convention. Don't overuse โ it complicates testing and flexibility. Keep things simple until you have a real reason to hide them.โฆ Key Takeaways
- A class is a blueprint; an object is an instance of that blueprint
__init__initializes objects.selfrefers to the current object inside methods- Instance attributes (in
__init__) are unique per object; class attributes are shared - Inheritance lets child classes reuse parent functionality and specialize it
- Use
super()to call parent methods from child classes without rewriting code __str__and__repr__make debugging easier by controlling how objects print- OOP is the foundation of every ML framework โ understanding it now scales to TensorFlow, PyTorch, and beyond
Ready to go further?
Join the Best AI Program: The AI-Era Analyst โ 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst โ