Python Classes and Objects for Beginners: OOP Basics with Simple Examples
P11.2 How to Add Methods to a Python Class
Why. Data and the actions on it belong together. account.deposit(100) is clearer than a loose function.
What. A method is a function written inside the class. It uses self to read and change the object's attributes.
How.
Add a method
- Inside the class, write
def name(self, ...):. - Use
self.attributeto read or update data. - Call it as
obj.name(...).
Worked example A — Deposit and withdraw.
Step 1 — What we do. We add actions to the account.
Step 2 — Type and run this code.
class Account:
def __init__(self, holder, balance=0):
self.holder = holder
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Not enough money")
else:
self.balance -= amount
a = Account("Emma", 500)
a.deposit(200)
a.withdraw(1000)
a.withdraw(300)
print(a.balance)
Step 3 — Output you should see.
Not enough money
400
Step 4 — What it means. 500 + 200 = 700; the 1000 withdrawal is refused; 700 - 300 = 400.
Worked example B — A method that returns text.
Step 1 — What we do. We add a nice summary using an f-string, for a shop order.
Step 2 — Type and run this code.
class Order:
def __init__(self, order_id, amount, currency="₹"):
self.order_id = order_id
self.amount = amount
self.currency = currency
def summary(self):
return f"{self.order_id}: {self.currency}{self.amount:,.2f}"
print(Order("BLK-1001", 1450).summary())
print(Order("NY-77", 89.5, "$").summary())
Step 3 — Output you should see.
BLK-1001: ₹1,450.00
NY-77: $89.50
Step 4 — What it means. The same method works for every object, with its own data.
Ravindra Bagale's Tip
When you write df.head() or text.upper(), you are calling a method on an object. Now you know where the dot comes from.
Ravindra Bagale's Tip – मराठी
df.head() किंवा text.upper() लिहिता तेव्हा तुम्ही object वर method call करता. आता dot कुठून येतो ते कळलं.
Ravindra Bagale's Tip – हिंदी
df.head() या text.upper() लिखते हो तो आप object पर method call करते हो. अब पता चला dot कहाँ से आता है.