Classes & Objects — Python OOP
ক্লাস ও অবজেক্ট — নিজের type তৈরি করা
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.
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 এটিই ব্যবহার করেন।
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")
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 শেয়ার করে।
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.
self থাকে। @classmethod-এ cls থাকে — alternative constructor-এর জন্য দরকারি। @staticmethod-এ কোনোটিই থাকে না — এটি শুধু namespace-এর জন্য class-এর ভেতরে রাখা একটি function।
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__ তৈরি করে দেয়।
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
| Term | Meaning | বাংলায় |
|---|---|---|
| Class | A blueprint for objects. | Object তৈরির blueprint। |
| Instance | A specific object created from a class. | একটি class থেকে তৈরি নির্দিষ্ট object। |
__init__ | Initialiser called automatically at creation time. | Object তৈরির সময় স্বয়ংক্রিয়ভাবে call হওয়া initialiser। |
self | Current instance reference (by convention). | বর্তমান instance-এর reference (convention)। |
@property | Method accessed like an attribute. | Attribute-এর মতো access হওয়া method। |
@dataclass | Auto-generates boilerplate. | স্বয়ংক্রিয়ভাবে boilerplate তৈরি করে। |
7. Practice Problems
-
Define a
Studentclass withnameandmarks, and a methodgrade()returning A/B/C/F based on marks.Studentclass লিখুন যারnameওmarksআছে এবংgrade()method A/B/C/F রিটার্ন করবে।✨ Show Answer
ans1.pyclass 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()) -
Write a
BankAccountclass that supportsdeposit,withdrawand abalanceproperty.BankAccountclass লিখুন —deposit,withdrawএবংbalanceproperty সহ।✨ Show Answer
ans2.pyclass 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) -
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
selfinside a method and belongs only to that particular object.Class attribute class-body-তে define হয় ও সব instance শেয়ার করে; class-এ পরিবর্তন করলে সব instance-এ প্রভাব পড়ে। Instance attribute
self-এর মাধ্যমে set হয় ও কেবল সেই নির্দিষ্ট object-এর। -
Use
@dataclassto write aBook(title, author, year)class and compare two books.@dataclassব্যবহার করেBook(title, author, year)লিখুন ও দুটি book তুলনা করুন।✨ Show Answer
ans4.pyfrom 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) -
Why is
selfa convention and not a keyword? Explain briefly.selfkeyword না হয়ে 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
selfis 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.
__init__ instance initialise করে, self method-কে তার নিজের ডেটা খুঁজে পেতে সাহায্য করে। পরবর্তী পাঠে আমরা inheritance ও dunder method শিখব।