Python Classes and Objects for Beginners: OOP Basics with Simple Examples
P11.1 What Is a Class and an Object in Python
Why. A bank has thousands of accounts. Each has a holder, a balance and the same actions: deposit, withdraw. A class describes this once; each account is an object.
What.
- Class — the blueprint (like a form template).
- Object — one filled copy (one customer's form).
- Attribute — a value stored in the object (
balance). - Method — a function that belongs to the object (
deposit()).
How.
Create a class and an object
- Write
class Name:. - Inside, define
__init__(self, ...)to set attributes. - Create an object:
obj = Name(...). - Read attributes with a dot:
obj.balance.
Worked example A — The simplest class.
Step 1 — What we do. An account class with a holder and a balance.
Step 2 — Type and run this code.
class Account:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
a = Account("Emma", 500)
print(a.holder, a.balance)
Step 3 — Output you should see.
Emma 500
Step 4 — What it means. self means "this object". self.holder = holder stores the value inside the object.
Worked example B — Two objects, one class.
Step 1 — What we do. Two customers at a bank in Sydney.
Step 2 — Type and run this code.
class Account:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
a = Account("Emma", 500)
b = Account("Jack", 1200)
print(a.holder, a.balance)
print(b.holder, b.balance)
Step 3 — Output you should see.
Emma 500
Jack 1200
Step 4 — What it means. Each object keeps its own values. Changing a does not touch b.
Ravindra Bagale's Tip
self is always the first parameter of a method. Python fills it in for you; you never pass it yourself.
Ravindra Bagale's Tip – मराठी
self हा नेहमी method चा पहिला parameter असतो. Python तो आपोआप भरतो; तुम्ही स्वतः देत नाही.
Ravindra Bagale's Tip – हिंदी
self हमेशा method का पहला parameter होता है. Python उसे अपने आप भरता है; आप खुद नहीं देते.