Ravindra BagaleCourses & study guides मराठी Track your progress

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

  1. Write class Name:.
  2. Inside, define __init__(self, ...) to set attributes.
  3. Create an object: obj = Name(...).
  4. Read attributes with a dot: obj.balance.
1. class Account: (the blueprint)2. Account("Emma", 500) is called3. __init__ fills the attributes4. You get one object: emma
From class to object (read from top to bottom)

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.