Classes & Objects — Python OOP

ক্লাস ও অবজেক্ট — নিজের type তৈরি করা

Read: ~35 min Intermediate 5 practice problems Live code runner

1. What Is a Class?

A class is a blueprint for creating objects. An object packages together some data (attributes) and some behaviour (methods). Once you define a class you can make as many instances of it as you want, each with its own state. Everything in Python — integers, strings, lists, functions, even modules — is already an object of some class.

একটি class হলো object তৈরির blueprint। একটি object-এ থাকে কিছু ডেটা (attribute) এবং কিছু আচরণ (method)। Python-এ সবকিছুই — integer, string, list, function, এমনকি module — কোনো না কোনো class-এর object।

2. Your First Class — Dog

__init__ is the constructor. self refers to the instance currently being built or operated on. Note: self is a convention, not a keyword — but every Python programmer uses it, and PEP 8 recommends it.

__init__ হলো constructor। self বর্তমান instance-কে নির্দেশ করে। self কোনো keyword নয় — এটি একটি convention মাত্র, কিন্তু সকল Python programmer এটিই ব্যবহার করেন।
dog.py
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says woof!"

d1 = Dog("Tommy", 3)
d2 = Dog("Rex", 5)
print(d1.bark())
print(d2.bark())
print(f"{d1.name} is {d1.age} years old")
class Dog __init__(self, name, age) bark(self) d1 (instance) name="Tommy", age=3 d2 (instance) name="Rex", age=5 Figure 22.1 — একটি class থেকে একাধিক instance।

3. Instance vs Class Attributes

Attributes set on self belong to a specific instance. Attributes set directly on the class body are shared by every instance.

self-এর মাধ্যমে set করা attribute কেবল একটি নির্দিষ্ট instance-এর। class body-তে সরাসরি set করা attribute সব instance শেয়ার করে।
counter.py
class Counter:
    total_created = 0              # class attribute — shared

    def __init__(self, label):
        self.label = label              # instance attribute
        Counter.total_created += 1

a = Counter("A")
b = Counter("B")
c = Counter("C")
print(a.label, b.label, c.label)
print("total created:", Counter.total_created)

4. Instance, Class and Static Methods

A regular method takes self. A @classmethod takes cls (the class itself) — useful for alternative constructors. A @staticmethod takes neither — it is just a function living inside a class for organisational reasons.

সাধারণ method-এ self থাকে। @classmethod-এ cls থাকে — alternative constructor-এর জন্য দরকারি। @staticmethod-এ কোনোটিই থাকে না — এটি শুধু namespace-এর জন্য class-এর ভেতরে রাখা একটি function।
methods.py
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def to_fahrenheit(self):
        return self.celsius * 9 / 5 + 32

    @classmethod
    def from_fahrenheit(cls, f):
        return cls((f - 32) * 5 / 9)

    @staticmethod
    def is_freezing_c(c):
        return c <= 0

t = Temperature(25)
print(t.to_fahrenheit())
print(Temperature.from_fahrenheit(212).celsius)
print(Temperature.is_freezing_c(-3))

5. @property and @dataclass

@property turns a method into a computed attribute — no parentheses at the call site. @dataclass (PEP 557) auto-generates __init__, __repr__, and __eq__ from the class's typed fields.

@property একটি method-কে computed attribute-এ রূপান্তর করে — call করার সময় বন্ধনী লাগে না। @dataclass (PEP 557) স্বয়ংক্রিয়ভাবে __init__, __repr__, __eq__ তৈরি করে দেয়।
point.py
from dataclasses import dataclass
from math import hypot

@dataclass
class Point:
    x: float
    y: float

    @property
    def distance_from_origin(self):
        return hypot(self.x, self.y)

p = Point(3, 4)
print(p)                         # Point(x=3, y=4)  auto-repr
print(p.distance_from_origin)   # 5.0 — no parentheses!
print(p == Point(3, 4))          # True — auto-eq

6. Vocabulary

TermMeaningবাংলায়
ClassA blueprint for objects.Object তৈরির blueprint।
InstanceA specific object created from a class.একটি class থেকে তৈরি নির্দিষ্ট object।
__init__Initialiser called automatically at creation time.Object তৈরির সময় স্বয়ংক্রিয়ভাবে call হওয়া initialiser।
selfCurrent instance reference (by convention).বর্তমান instance-এর reference (convention)।
@propertyMethod accessed like an attribute.Attribute-এর মতো access হওয়া method।
@dataclassAuto-generates boilerplate.স্বয়ংক্রিয়ভাবে boilerplate তৈরি করে।

7. Practice Problems

  1. Define a Student class with name and marks, and a method grade() returning A/B/C/F based on marks.
    Student class লিখুন যার name ও marks আছে এবং grade() method A/B/C/F রিটার্ন করবে।
    ✨ Show Answer
    ans1.py
    class Student:
        def __init__(self, name, marks):
            self.name = name
            self.marks = marks
    
        def grade(self):
            if self.marks >= 80: return "A"
            if self.marks >= 70: return "B"
            if self.marks >= 50: return "C"
            return "F"
    
    for m in [92, 74, 55, 30]:
        s = Student("X", m)
        print(m, "→", s.grade())
  2. Write a BankAccount class that supports deposit, withdraw and a balance property.
    BankAccount class লিখুন — deposit, withdraw এবং balance property সহ।
    ✨ Show Answer
    ans2.py
    class BankAccount:
        def __init__(self, owner, start=0):
            self.owner = owner
            self._balance = start
    
        @property
        def balance(self):
            return self._balance
    
        def deposit(self, amount):
            self._balance += amount
    
        def withdraw(self, amount):
            if amount > self._balance:
                raise ValueError("insufficient funds")
            self._balance -= amount
    
    acc = BankAccount("Arif", 1000)
    acc.deposit(500)
    acc.withdraw(300)
    print(acc.owner, "balance:", acc.balance)
  3. Explain in two sentences the difference between a class attribute and an instance attribute.
    দুই বাক্যে class attribute ও instance attribute-এর পার্থক্য ব্যাখ্যা করুন।
    ✨ Show Answer

    Answer: A class attribute is defined in the class body and is shared by every instance — changing it on the class affects all instances. An instance attribute is set on self inside a method and belongs only to that particular object.

    Class attribute class-body-তে define হয় ও সব instance শেয়ার করে; class-এ পরিবর্তন করলে সব instance-এ প্রভাব পড়ে। Instance attribute self-এর মাধ্যমে set হয় ও কেবল সেই নির্দিষ্ট object-এর।

  4. Use @dataclass to write a Book(title, author, year) class and compare two books.
    @dataclass ব্যবহার করে Book(title, author, year) লিখুন ও দুটি book তুলনা করুন।
    ✨ Show Answer
    ans4.py
    from dataclasses import dataclass
    
    @dataclass
    class Book:
        title: str
        author: str
        year: int
    
    a = Book("Pather Panchali", "Bibhutibhushan", 1929)
    b = Book("Pather Panchali", "Bibhutibhushan", 1929)
    print(a)
    print("equal:", a == b)
  5. Why is self a convention and not a keyword? Explain briefly.
    self keyword না হয়ে convention কেন?
    ✨ Show Answer

    Answer: Python passes the instance as the first argument to every instance method; the parameter could legally be called anything. Guido's reasoning was that explicit is better than implicit — showing the instance as an ordinary parameter keeps method definitions uniform with functions. Calling it anything other than self is legal but breaks every reader's expectations and PEP 8.

    Python প্রতিটি instance method-এর প্রথম argument হিসেবে instance-কে pass করে; এর নাম যা খুশি রাখা যায়। কিন্তু PEP 8 এবং সকল programmer-এর অভ্যাস অনুযায়ী self-ই ব্যবহৃত হয়।

Summary — Module 22

A class bundles state and behaviour. __init__ initialises each instance, self is how a method finds its own data. Use @classmethod for alternative constructors, @staticmethod for namespace-only helpers, @property for computed attributes, and @dataclass for simple record-like types. The rest of OOP — inheritance, polymorphism, dunder methods — builds on top of what you just learned.

একটি class state ও behaviour একত্রে bundle করে। __init__ instance initialise করে, self method-কে তার নিজের ডেটা খুঁজে পেতে সাহায্য করে। পরবর্তী পাঠে আমরা inheritance ও dunder method শিখব।

Next Module → Inheritance, Polymorphism & Dunder Methods।