Going Further Lesson 22 of 23
Python Classes and Objects
Object-oriented programming in Python — define classes with __init__ and self, add methods, create objects, use __str__, and extend classes with inheritance.
As programs grow, you'll want to bundle data and the actions on that data together. A class is a blueprint for creating objects that have their own data (attributes) and actions (methods). This style is called object-oriented programming (OOP), and it's used in Python, Java, C++, C# and JavaScript.
Defining a class
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
self.scores = []
def add_score(self, score):
self.scores.append(score)
def average(self):
if not self.scores:
return 0
return sum(self.scores) / len(self.scores)
ana = Student("Ana", 9)
ana.add_score(88)
ana.add_score(94)
ben = Student("Ben", 10)
ben.add_score(79)
print(ana.name, ana.average())
print(ben.name, ben.average())
Output
Ana 91.0 Ben 79.0
The key parts:
class Student:starts the blueprint. Class names use CapitalizedWords.__init__(two underscores on each side) runs automatically when an object is created. It sets up the starting data.selfmeans "this particular object".self.name = namestores the name inside the object.- Methods are functions inside the class. Their first parameter is always
self. Student("Ana", 9)creates an object (an instance). You don't passself; Python does that for you.
Each object has its own data
ana and ben were made from the same class, but each has its own name, grade and scores. Changing one doesn't affect the other, just like two students can share the same form but fill it in differently.
__str__: how an object prints
class Product:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def __str__(self):
return f"{self.name} – ₱{self.price:.2f} ({self.stock} left)"
def sell(self, qty):
if qty > self.stock:
print(f"Not enough {self.name}!")
return 0
self.stock -= qty
return self.price * qty
kape = Product("Kape 3-in-1", 8, 200)
print(kape)
print("Sale:", kape.sell(5))
print(kape)
kape.sell(500)
Output
Kape 3-in-1 – ₱8.00 (200 left) Sale: 40 Kape 3-in-1 – ₱8.00 (195 left) Not enough Kape 3-in-1!
Without __str__, print(kape) would show something unhelpful like <__main__.Product object at 0x10a3b...>.
Inheritance
A class can inherit from another, getting all its attributes and methods, and adding or changing some:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient balance.")
else:
self.balance -= amount
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.02):
super().__init__(owner, balance) # set up the Account part
self.rate = rate
def add_interest(self):
self.balance += self.balance * self.rate
acct = SavingsAccount("Juan", 1000)
acct.deposit(500)
acct.add_interest()
print(acct.owner, round(acct.balance, 2))
acct.withdraw(5000)
Output
Juan 1530.0 Insufficient balance.
SavingsAccount is an Account with extra features. super().__init__(...) runs the parent's setup so we don't repeat that code.
Class attributes
An attribute defined directly in the class (not in __init__) is shared by all objects:
class Student:
school = "Mabini National High School" # shared by everyone
def __init__(self, name):
self.name = name # different per student
a = Student("Ana")
b = Student("Ben")
print(a.school == b.school)
Output
True
Why use classes?
- Organization: data and the functions that use it live together.
- Reuse: create as many objects as you need from one class.
- Modeling: real things like students, products, accounts and game characters map naturally to classes.
- Extension: inheritance lets you build specialized versions without copying code.
For small scripts, functions and dictionaries are enough. Reach for classes when you have many "things" of the same kind, each with data and behavior.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04