Download The Ultimate Beginner's Guide to Object-Oriented Programming (OOP) and more Study notes Object Oriented Programming in PDF only on Docsity!
Object-Oriented
Programming
The Complete Beginner's Course Guide
Learn with Real-Life Examples · No Prior Experience Needed
Classes · Objects · Inheritance · Polymorphism · Encapsulation · Abstraction
Beginner Friendly Edition | 2025
n Table of Contents
Chapter 1: What is OOP? (And Why Should You Care?)
› What is a Program?
› Procedural vs OOP Thinking
› The 4 Pillars Overview
Chapter 2: Classes and Objects – The Building Blocks
› What is a Class?
› What is an Object?
› Attributes & Methods
› Real-Life Blueprint Analogy
Chapter 3: Encapsulation – Privacy Matters!
› What is Encapsulation?
› Public vs Private
› Getters & Setters
› Real-Life ATM Example
Chapter 4: Inheritance – Don't Repeat Yourself!
› What is Inheritance?
› Parent & Child Classes
› Overriding Methods
› Real-Life Vehicle Example
Chapter 5: Polymorphism – Many Forms!
› What is Polymorphism?
› Method Overloading
› Method Overriding
› Real-Life Shape Example
Chapter 6: Abstraction – Hide the Complexity!
› What is Abstraction?
› Abstract Classes
› Interfaces
› Real-Life TV Remote Example
Chapter 7: Putting It All Together – Build a Mini Project
› Project: School Management System
› Step-by-Step Code
› Full Walkthrough
Chapt
er 1 What is OOP?
And Why Should You Care?
1.1 What is a Program?
Think of a program as a set of instructions you give to a computer — just like a recipe tells you
how to cook a dish. Before OOP existed, programmers wrote code as one long list of instructions
(called procedural programming ). It worked fine for small programs, but as programs got
bigger, things became messy and hard to manage.
n n Real Life: Cooking Recipe
Imagine making a 3-course dinner. If you write all the steps from starter to dessert in one giant
list with no sections, it gets confusing fast. OOP is like organising your recipe into separate
cards: one for the starter, one for the main, one for dessert. Each card is self-contained and
reusable!
1.2 Procedural vs Object-Oriented Thinking
Feature Procedural (Old Way) Object-Oriented (OOP)
Focus Functions & logic Objects & data
Code reuse Copy-paste functions Inheritance & classes
Organisation Top-to-bottom scripts Modular objects
Real-life fit Step-by-step recipes Things & their behaviour
Maintenance Hard as it grows Easy to extend & modify
1.3 The 4 Pillars of OOP
Everything in OOP rests on four main ideas. Don't worry — we'll explore each one with fun
real-life examples throughout this guide.
n
Encapsulation
Bundling data and methods together, and hiding private details.
Example: Like your phone's PIN – the screen shows the keypad but hides the verification logic.
n
Inheritance
A child class inherits properties from a parent class.
Example: Like a child inheriting eye colour or height from parents.
n
Polymorphism
The same action can behave differently in different situations.
Example: Like the word 'run' — a person runs, a program runs, a colour runs in the wash!
n
Abstraction
Showing only what's necessary, hiding complex internals.
Example: Like a car steering wheel — you turn it without knowing the engineering underneath.
n Tip: OOP is used in almost every major software you use daily — Instagram, WhatsApp,
games, banking apps. Learning it opens enormous doors!
2.4 Your First Class – Python Example
Let's write a simple Dog class together. Read each line carefully:
Define the class (the blueprint)
class Dog:
Constructor – runs when we create a new dog
def init(self, name, breed, age): self.name = name # Attribute: the dog's name self.breed = breed # Attribute: the breed self.age = age # Attribute: the age
Method – something the dog can DO
def bark(self): print(f'{self.name} says: Woof! Woof!')
def describe(self): print(f'I am {self.name}, a {self.age}-year-old {self.breed}.')
Create objects (actual dogs!)
dog1 = Dog('Buddy', 'Golden Retriever', 3) dog2 = Dog('Max', 'Poodle', 5)
Use the objects
dog1.bark() # Output: Buddy says: Woof! Woof! dog2.describe() # Output: I am Max, a 5-year-old Poodle.
n Tip: Notice: we defined the class ONCE but created multiple dogs from it. This is the
superpower of OOP – write once, use many times!
Chapt
er 3 Encapsulation
Protect Your Data Like a Pro!
3.1 What is Encapsulation?
Encapsulation means wrapping data (attributes) and methods together inside a class , and
restricting direct access to some of the object's components. It's about protecting data from
accidental changes.
n n Real Life: ATM Machine
When you use an ATM, you can: check balance, deposit money, withdraw cash.
But you CANNOT: directly change your balance in the bank's database, access other people's
accounts, modify the ATM's internal code.
The ATM exposes ONLY what you need (a simple screen + buttons) while HIDING all the
complex banking logic behind the scenes. That's Encapsulation!
n n Real Life: Medicine Capsule
A capsule (pill) bundles the medicine inside a protective coating. You can't directly access the
powder inside — you take the whole capsule. The coating protects the medicine and controls
how it's released. Encapsulation works the same way with data!
3.2 Public vs Private
Access Level Who Can Use It? Python Syntax Real Life
Public Anyone, anywhere self.name Your name on a name badge
Protected Class & subclasses self._salary Staff-only area in a shop
Private Only inside that class self.__pin Your secret bank PIN
3.3 Getters & Setters
Since private data can't be accessed directly, we use special methods called getters (to read
data) and setters (to update data safely). This lets us add validation rules.
class BankAccount: def init(self, owner, balance): self.owner = owner # Public – anyone can see the name
Chapt
er 4 Inheritance
Don't Repeat Yourself – Reuse!
4.1 What is Inheritance?
Inheritance allows a new class (child) to automatically receive all the attributes and methods of
an existing class (parent). The child can then add new features or change existing ones. This
promotes code reuse — you write the common stuff once!
n n Real Life: Vehicles
All vehicles share common features: they have wheels, an engine, they can start, stop, and
move.
A Car is a vehicle + has 4 doors, a boot, plays music.
A Motorcycle is a vehicle + has 2 wheels, no boot, has a kickstand.
A Truck is a vehicle + has a cargo area, bigger engine, more wheels.
Instead of rewriting 'start engine' for each one, they all INHERIT it from Vehicle!
n nnnnn Real Life: Family Inheritance
Parents pass on traits to children: eye colour, height, surname, language.
Children can also have their OWN traits that parents don't have.
In OOP: the child class inherits everything from the parent, and can add extra
methods/attributes.
4.2 Inheritance in Code
PARENT class – has common features all animals share
class Animal: def init(self, name, age): self.name = name self.age = age
def eat(self): print(f'{self.name} is eating.')
def sleep(self): print(f'{self.name} is sleeping.')
def describe(self): print(f'I am {self.name}, aged {self.age}.')
CHILD class – inherits from Animal
class Dog(Animal): # <-- (Animal) means 'inherit from Animal' def init(self, name, age, breed): super().init(name, age) # Call parent's init self.breed = breed # Dog's OWN attribute
def bark(self): # Dog's OWN method print(f'{self.name} says: Woof!')
ANOTHER child class
class Cat(Animal): def init(self, name, age, indoor): super().init(name, age) self.indoor = indoor
def meow(self): print(f'{self.name} says: Meow!')
Test
buddy = Dog('Buddy', 3, 'Labrador') buddy.eat() # Inherited from Animal → Buddy is eating. buddy.bark() # Dog's own method → Buddy says: Woof!
kitty = Cat('Kitty', 2, True) kitty.sleep() # Inherited from Animal → Kitty is sleeping. kitty.meow() # Cat's own method → Kitty says: Meow!
4.3 Types of Inheritance
Type Meaning Example
Single One child, one parent Dog inherits from Animal
Multiple One child, multiple parents FlyingFish inherits from Fish & Bird
Multilevel Grandparent → Parent → Child Animal→Dog→GoldenRetriever
Hierarchical Many children, one parent Animal → Dog, Cat, Bird
n Tip: super() is magical! It calls the parent class's method, so you don't have to rewrite the
parent's init code. Always use it in child constructors.
class Cat(Animal): def speak(self): return f'{self.name} says: Meow!'
class Duck(Animal): def speak(self): return f'{self.name} says: Quack!'
Create a list of different animals
animals = [Dog('Buddy'), Cat('Kitty'), Duck('Donald')]
Polymorphism in action – same method, different behaviour!
for animal in animals: print(animal.speak())
Output:
Buddy says: Woof!
Kitty says: Meow!
Donald says: Quack!
5.3 Why is Polymorphism Useful?
Imagine you're building a drawing app with many shapes. Without polymorphism:
WITHOUT Polymorphism – messy!
def draw_all(shapes): for s in shapes: if type(s) == Circle: draw_circle(s) elif type(s) == Square: draw_square(s) elif type(s) == Triangle: draw_triangle(s) # Gets longer with each new shape!
With polymorphism:
WITH Polymorphism – clean and elegant!
def draw_all(shapes): for shape in shapes: shape.draw() # Each shape knows how to draw itself!
Adding a new shape later? Just add a new class with draw()
No need to change draw_all() at all!
n Tip: Polymorphism makes adding new features easy! Add a new animal, shape, or vehicle
class without touching existing code. This is called the Open/Closed Principle.
Chapt
er 6 Abstraction
Show Only What's Needed!
6.1 What is Abstraction?
Abstraction means hiding complex implementation details and only showing the essential
features. Users interact with a simple interface without needing to understand the complex logic
underneath.
n n Real Life: TV Remote Control
When you press the 'Volume Up' button on your TV remote, you don't need to know:
- How the infrared signal is generated and transmitted
- How the TV receiver decodes the signal
- How the speaker amplifier adjusts voltage levels
You just press a button and volume goes up! The remote ABSTRACTS all that complexity into
a simple interface: buttons. That's abstraction!
n n Real Life: Driving a Car
To drive, you need to know: steering wheel, accelerator, brake, gear shift.
You don't need to know: how pistons fire in the engine, how hydraulic brakes work, how the
transmission converts torque... The car abstracts all that complexity.
6.2 Abstract Classes in Python
An abstract class is like a template that says 'every class that inherits me MUST implement
these methods'. You can't create objects directly from an abstract class — it's just a contract or
blueprint.
from abc import ABC, abstractmethod
Abstract class – a 'contract' for all payment types
class Payment(ABC): @abstractmethod def pay(self, amount): # Every payment method MUST implement this pass
@abstractmethod def get_receipt(self): pass
Chapt
er 7 Putting It All Together
Build a School Management System!
7.1 Project Overview
We'll build a simple School Management System that uses ALL 4 OOP pillars. This is a
real-world style project you can expand on!
- Person (base class) — Common attributes for all school members
- Student (child class) — Inherits from Person, adds grade & marks
- Teacher (child class) — Inherits from Person, adds subject & salary
- School (main class) — Manages lists of students and teachers
7.2 The Full Code
nn ABSTRACTION: Abstract base nnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
from abc import ABC, abstractmethod
class Person(ABC): def init(self, name, age, id_number): self.name = name # Public self.age = age # Public self.__id = id_number # Private (ENCAPSULATION)
def get_id(self): # Getter for private ID return self.__id
@abstractmethod def describe(self): # Must be implemented by children pass
def greet(self): print(f'Hello! I am {self.name}.')
nn INHERITANCE: Student inherits Person nnnnnnnnnnnnnnnnnnnnn
class Student(Person): def init(self, name, age, id_number, grade): super().init(name, age, id_number) self.grade = grade self.__marks = [] # Private list of marks
def add_mark(self, subject, mark): self.__marks.append({'subject': subject, 'mark': mark})
def get_average(self): if not self.__marks: return 0 return sum(m['mark'] for m in self.__marks) / len(self.__marks)
def describe(self): # POLYMORPHISM: own implementation avg = self.get_average() print(f'Student: {self.name} | Grade: {self.grade} | Average: {avg:.1f }%')
nn INHERITANCE: Teacher inherits Person nnnnnnnnnnnnnnnnnnnnn
class Teacher(Person): def init(self, name, age, id_number, subject): super().init(name, age, id_number) self.subject = subject self.__salary = 0 # Private
def set_salary(self, amount): if amount > 0: self.__salary = amount
def describe(self): # POLYMORPHISM: own implementation print(f'Teacher: {self.name} | Subject: {self.subject}')
def teach(self): print(f'{self.name} is teaching {self.subject}.')
nn School class nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
class School: def init(self, school_name): self.name = school_name self.__students = [] self.__teachers = []
def enroll(self, student): self.__students.append(student) print(f'{student.name} enrolled at {self.name}.')
def hire(self, teacher): self.__teachers.append(teacher) print(f'{teacher.name} hired at {self.name}.')
def show_all(self): # POLYMORPHISM: calls describe() on each print(f'\n=== {self.name} – All Members ===') for person in self.__students + self.__teachers: person.describe() # Same call, different output!
nn Run the program nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
school = School('Sunrise Academy')
Chapt
er 8
Common Mistakes & Quick
Reference
Avoid These Traps!
8.1 Top 10 Beginner Mistakes
#1 — Forgetting self
Every method in a class must have 'self' as the first parameter.
def bark(): ← WRONG def bark(self): ← CORRECT
#2 — Not calling super()
In a child class constructor, always call super().init() to initialise the parent's attributes.
def init(self, name, breed):
Forgot super()! Parent attributes won't be set
#3 — Confusing class and object
The class is the blueprint; the object is the real thing. dog = Dog() creates an object. Dog itself is
just the template.
#4 — Mutable default arguments
Never use a list or dict as a default parameter in a method. All instances will share it!
#5 — Overusing inheritance
Not everything needs to inherit. If a class only uses another for one method, consider
composition instead.
#6 — Ignoring encapsulation
Don't make everything public. Ask: should outsiders be able to change this? If not, make it
private.
#7 — Not naming classes with CapitalCase
Use MyClass, not myclass or my_class. This is Python convention.
#8 — Huge classes with many responsibilities
One class = one responsibility. A 'God class' that does everything is hard to maintain.
#9 — Forgetting to return in getters
A getter must return the value: return self.__balance. Without return it returns None!
#10 — Comparing objects with ==
Two objects with the same data are NOT equal by default. You must implement eq if you
want == to work.