๐Ÿงฑ 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.

class = blueprint | object = instance

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

Classes
Blueprints
Templates defining an object's structure and methods.
Objects
Instances
Actual things created from a class blueprint.
Inheritance
Reuse
Child classes inherit traits from parent classes.
Encapsulation
Privacy
Hide internal details; expose only what's needed.

๐Ÿฆ The Business Scenario

๐Ÿฆ
Banking ยท SouthBank India, Mumbai
Modeling Bank Accounts with Classes

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.

3
Account types
5
Code blocks
2
Inheritance levels

๐Ÿ’ป 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.

bank_account.py โ–ถ Run to see output below
# Output Priya Sharma: โ‚น50,000.00 Arjun Kapoor: โ‚น75,000.00 โ‚น15000 deposited. New balance: โ‚น65,000.00 โ‚น10000 withdrawn. New balance: โ‚น65,000.00

๐Ÿ”ค 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.

account_with_str.py โ–ถ Better output
# Output Priya Sharma โ€” Balance: โ‚น50,000.00 BankAccount('Priya Sharma', 50000) After deposit: Priya Sharma โ€” Balance: โ‚น70,000.00

๐Ÿ“ˆ 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.

inheritance_example.py โ–ถ Extending functionality
# Output Savings: Priya Sharma โ€” โ‚น100,000.00 Interest earned: โ‚น5,000.00 Current: Arjun Kapoor โ€” โ‚น-10,000.00

โšก 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.

super_and_override.py โ–ถ Custom behavior
# Output Withdraw โ‚น12,000 from standard? False Withdraw โ‚น9,000 from premium (fee=โ‚น50)? True Premium balance after: โ‚น950.00

๐Ÿท๏ธ 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.

class_vs_instance.py โ–ถ Understanding scope
# Output Bank: SouthBank India Total accounts: 3 Priya Sharma (ACC-00000): โ‚น50,000.00 Arjun Kapoor (ACC-00001): โ‚น75,000.00 Chidi Okafor (ACC-00002): โ‚น30,000.00

๐ŸŒ Also Used In

OOP Across Every Domain

๐Ÿ“ฑ
class Subscriber: balance, plan_type, top_up()
Telecom โ€” every billing system uses account classes
๐Ÿฅ
class MedicalRecord: patient_id, prescriptions, add_note()
Healthcare โ€” patient records are class instances
๐Ÿšš
class Shipment: tracking_id, status, update_location()
Logistics โ€” packages tracked with object state
๐Ÿค–
class NeuralNetwork: layers, weights, train()
AI & ML โ€” neural networks are class hierarchies

๐Ÿค– 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.

TensorFlow PyTorch scikit-learn Keras

๐ŸŽฏ Mini Challenge

Build an M-Pesa Transaction Class

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.

Start with 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).
A class is a blueprint or template (like a recipe). An object is an actual thing created from that blueprint (the actual cake you bake). You define a class once: 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.
Class attributes are defined in the class body (outside __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.
Inheritance lets a child class inherit attributes and methods from a parent class. Example: 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.
Composition means creating objects as attributes of other objects. Inheritance means extending a parent class. Use composition when the relationship is "has-a" (a person *has* a bank account); use inheritance for "is-a" (a savings account *is a* bank account). A common pitfall: beginners over-inherit. Instead of 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

Question 1 of 5
What does __init__ do in a Python class?
Question 2 of 5
In the line acc1.withdraw(500), what does self refer to?
Question 3 of 5
Which is true about class attributes?
Question 4 of 5
What does super() do?
Question 5 of 5
What does __str__ return, and when is it called?
0
/5

๐Ÿ“‹ Quick Cheatsheet

ConceptSyntaxPurpose
classclass Name:Define a class blueprint
__init__def __init__(self, ...):Initialize instance attributes
selfself.attr = valueReference current object
Instance attrself.balance = 1000Unique per object
Class attrbank_name = "SouthBank"Shared by all instances
Methoddef deposit(self, amount):Function inside a class
Inheritanceclass 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

Forgetting self in method definitions
Every method in a class needs self 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.
Confusing class and instance attributes
Define instance attributes in __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.
Not using super().__init__ in child classes
If the parent class has __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.
Making everything private with underscores too early
Python uses _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. self refers 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
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

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 โ†’