Skip to content

Module 11 · Object-Oriented Programming — topic 1 of 25

Introduction to OOP

What object-oriented programming is, how it differs from procedural code, the four pillars (encapsulation, inheritance, polymorphism, abstraction) and when classes are worth using.

Beginner 10 min read·Lesson 158 of 306 in Python Programming

Learning objectives

  • Explain the idea of objects that combine data and behaviour
  • Name the four pillars of OOP
  • Decide when a class is a better fit than functions and dictionaries

Definition

Object-oriented programming (OOP) is a style of programming that organises code around objects — bundles of data (attributes) and behaviour (methods) — created from classes that describe them.

Introduction

So far you have stored data in variables, lists and dictionaries, and written functions that operate on them. That works well for small programs. As programs grow, it becomes hard to keep track of which functions are allowed to touch which data.

Object-oriented programming groups the data and the functions that work on it into one unit, an object. A BankAccount object holds a balance and knows how to deposit and withdraw; the rest of the program just asks it to.

Why it matters

Everything in Python is already an object: strings have .upper(), lists have .append(), files have .read(). Learning OOP lets you design your own types with the same convenience.

Frameworks such as Django, Flask, pandas and pygame are built around classes, so understanding OOP is required to use them well.

Detailed explanation

A class is a blueprint; an object (or instance) is a thing built from it. One Student class can produce thousands of student objects, each with its own name and marks.

Encapsulation: an object keeps its data together with the methods that maintain it, and controls how the outside world changes it.

Inheritance: a class can extend another, reusing its code and adding or changing behaviour (a SavingsAccount is an Account).

Polymorphism: different classes can provide methods with the same name, so code can call shape.area() without caring which shape it has.

Abstraction: users of a class need to know what it does, not how — the details are hidden behind a simple interface.

Not everything needs a class. Small scripts and pure data transformations are often clearer as functions. Classes help when data and behaviour belong together and there are many objects of the same kind, or when you need several interchangeable implementations.

Syntax

Python
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner # data (attributes)
self.balance = balance
def deposit(self, amount): # behaviour (methods)
self.balance += amount
acc = BankAccount("Asha") # an object
acc.deposit(500)
  • class defines a new type.
  • Objects hold their own attribute values.
  • Methods are functions that belong to the class.

Code examples

Built-in objects already have methods

Python
name = "asha rao"
marks = [72, 95]
print(name.title(), type(name).__name__)
marks.append(88)
print(marks, type(marks).__name__)
print(isinstance(5, object), isinstance(len, object))
Output
Asha Rao str
[72, 95, 88] list
True True

Procedural versus object-oriented

Python
# procedural: data and functions are separate
account = {"owner": "Asha", "balance": 0}
def deposit(acc, amount):
acc["balance"] += amount
deposit(account, 500)
print(account["balance"])
# object-oriented: data and behaviour together
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
self.balance += amount
acc = Account("Asha")
acc.deposit(500)
print(acc.balance)
Output
500
500

More examples

Many objects from one class

Python
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
return False
self.balance -= amount
return True
accounts = [Account("Asha", 1000), Account("Ravi"), Account("Meera", 250)]
accounts[1].deposit(400)
print(accounts[2].withdraw(500), accounts[0].withdraw(300))
for a in accounts:
print(f"{a.owner:<6} {a.balance:>5}")
Output
False True
Asha     700
Ravi     400
Meera    250

Step-by-step explanation

  • The Account class describes what every account has (owner, balance) and can do (deposit, withdraw).
  • Three objects are created; each keeps its own balance.
  • withdraw enforces a rule — no overdrafts — so no code outside the class can break it by accident.
  • The loop treats all accounts uniformly through their attributes.

Expected output

Running “Many objects from one class” prints exactly:

TextOutput
False True
Asha 700
Ravi 400
Meera 250

Practical applications

  • Games model players, enemies and items as objects.
  • Web frameworks represent requests, responses and database rows as objects.
  • GUI toolkits represent windows and buttons as objects.

Best practices

  • Use classes when data and behaviour belong together.
  • Keep each class focused on one concept.
  • Start simple; add inheritance only when there is a real 'is-a' relationship.

Common mistakes

Classes for everything

Avoid

class Calculator:
def add(self, a, b):
return a + b

Prefer

def add(a, b):
return a + b

A class with no data is usually just a function in disguise.

Important notes

  • Python supports several styles at once; mixing functions and classes appropriately is normal.

Key takeaways

  • OOP organises code into objects combining data and behaviour.
  • Classes are blueprints; objects are instances.
  • The four pillars are encapsulation, inheritance, polymorphism and abstraction.

Try it yourself

  1. 1
    List three real-world things you could model as classes, with two attributes and two methods each.
  2. 2
    Rewrite a dictionary-plus-functions program as a class.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module