Classes & OOP
class, __init__, self, inheritance, and dunder methods
Skills taught: python.classes, python.inheritance, python.dunder-methods
Defining and using classes
class BankAccount:
# Class attribute — shared by all instances
interest_rate = 0.05
def __init__(self, owner, balance=0):
# Instance attributes — unique to each object
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
raise ValueError('Insufficient funds')
self.balance -= amount
return self.balance
def __str__(self):
return f'BankAccount({self.owner}: ₹{self.balance:,.2f})'
def __repr__(self):
return f'BankAccount(owner={self.owner!r}, balance={self.balance})'
# Create objects (instances)
acc1 = BankAccount('Prashant', 1000)
acc2 = BankAccount('Alice') # balance defaults to 0
acc1.deposit(500)
acc1.withdraw(200)
print(acc1) # BankAccount(Prashant: ₹1,300.00)
print(acc2.balance) # 0
print(BankAccount.interest_rate) # 0.05 (class attribute)
Inheritance
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f'{self.name} says {self.sound}!'
def __str__(self):
return f'{type(self).__name__}({self.name})'
# Inherit from Animal
class Dog(Animal):
def __init__(self, name):
super().__init__(name, 'Woof') # call parent __init__
def fetch(self, item):
return f'{self.name} fetched the {item}!'
class Cat(Animal):
def __init__(self, name):
super().__init__(name, 'Meow')
def speak(self): # override parent method
return f'{self.name} says {self.sound}... maybe.'
dog = Dog('Rex')
cat = Cat('Whiskers')
print(dog.speak()) # Rex says Woof!
print(cat.speak()) # Whiskers says Meow... maybe.
print(dog.fetch('ball')) # Rex fetched the ball!
print(isinstance(dog, Animal)) # True — Dog IS an Animal
@property and @dataclass
# @property — computed attribute
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError('Below absolute zero!')
self._celsius = value
@property
def fahrenheit(self): # read-only computed property
return self._celsius * 9/5 + 32
t = Temperature(100)
print(t.fahrenheit) # 212.0
t.celsius = 0 # uses setter
print(t.fahrenheit) # 32.0
# @dataclass — auto-generates __init__, __repr__, __eq__
from dataclasses import dataclass, field
@dataclass
class Point:
x: float
y: float
label: str = '' # optional with default
def distance_to_origin(self) -> float:
return (self.x**2 + self.y**2) ** 0.5
p = Point(3, 4)
print(p) # Point(x=3, y=4, label='')
print(p.distance_to_origin()) # 5.0
print(p == Point(3, 4)) # True — auto __eq__
Frequently Asked Questions
What is the difference between __str__ and __repr__?
__str__ is for human-readable output — what print() shows. __repr__ is for developer-readable output — what you see in the REPL or repr(). If only one is defined, __repr__ is used as fallback for both. Good __repr__ should ideally show how to recreate the object.
When should I use @dataclass instead of a regular class?
@dataclass is great when your class is primarily a data container. It auto-generates __init__, __repr__, and __eq__ based on field annotations. Use a regular class when you need custom __init__ logic, complex methods, or inheritance from non-dataclass bases.