Lesson 283 of 296
Python classes, errors and modules
What you will learn
- Classes, __init__ and self
- Special ("dunder") methods
- Dataclasses
- Inheritance
- Exceptions: try, except, else, finally, raise
- The with statement
- Modules, imports, virtual environments and pip
On this page
Classes
class BankAccount:
bank_name = "Python Bank" # class attribute, shared by all accounts
def __init__(self, owner: str, balance: float = 0):
self.owner = owner # instance attributes
self.balance = balance
def deposit(self, amount: float) -> None:
if amount <= 0:
raise ValueError("Amount must be positive")
self.balance += amount
acc = BankAccount("Sam")
acc.deposit(50)
print(acc.owner, acc.balance, acc.bank_name) # Sam 50 Python BankCompared with TypeScript:
__init__is the constructor.selfis likethis, but you must write it as the first parameter of every method.- There is no
new: you call the class like a function. - There is no real
private. By convention, a name starting with_means "internal, do not use from outside".
Special (dunder) methods
Methods with double underscores, such as __init__, let your class work with Python's built-in features.
class Money:
def __init__(self, pence: int):
self.pence = pence
def __repr__(self) -> str: # how it prints
return f"Money({self.pence})"
def __eq__(self, other: object) -> bool: # ==
return isinstance(other, Money) and self.pence == other.pence
def __add__(self, other: "Money") -> "Money": # +
return Money(self.pence + other.pence)
print(Money(150) + Money(50)) # Money(200)
print(Money(5) == Money(5)) # TrueWithout __eq__, == compares identity (the same object), just like === on objects in JavaScript.
Dataclasses
A dataclass writes __init__, __repr__ and __eq__ for you. It is the usual way to make simple data objects.
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
tags: list[str] = field(default_factory=list) # safe mutable default
@dataclass(frozen=True) # immutable
class Point:
x: int
y: int
p = Product("Pen", 1.5)
print(p) # Product(name='Pen', price=1.5, tags=[])
print(Point(1, 2) == Point(1, 2)) # TrueInheritance
class Animal:
def __init__(self, name: str):
self.name = name
def speak(self) -> str:
return "..."
class Dog(Animal):
def __init__(self, name: str, breed: str):
super().__init__(name) # call the parent constructor
self.breed = breed
def speak(self) -> str: # override
return "Woof"
d = Dog("Rex", "Collie")
print(d.name, d.speak(), isinstance(d, Animal)) # Rex Woof TruePython also supports abstract classes with the abc module, and Protocols (typing.Protocol) for structural typing, similar to TypeScript interfaces.
Exceptions
Python uses exceptions like throw and catch in TypeScript, with different words.
def parse_age(text: str) -> int:
try:
age = int(text)
except ValueError:
print("not a number")
return -1
else:
print("parsed fine") # runs only if no exception happened
return age
finally:
print("always runs")
print(parse_age("42"))
print(parse_age("abc"))
class OutOfStockError(Exception): # your own exception type
pass
try:
raise OutOfStockError("Pen is out of stock")
except OutOfStockError as e:
print(f"Error: {e}")| TypeScript | Python |
|---|---|
throw new Error("x") | raise ValueError("x") |
catch (e) | except ValueError as e: |
finally | finally: |
Catch specific exceptions. A bare except: catches everything, even Ctrl+C, and hides bugs.
The with statement
with sets something up and always cleans it up, even if an error happens. It is used for files, locks and database connections.
with open("notes.txt", "w") as f:
f.write("hello\n")
# the file is closed here automatically
with open("notes.txt") as f:
print(f.read().strip()) # helloModules, imports and packages
Every .py file is a module. Import from the standard library, your own files, or installed packages.
import math
from datetime import date
from collections import Counter as C
print(math.sqrt(16), date(2026, 1, 1).year, C("aab")["a"]) # 4.0 2026 2
def main() -> None:
print("running as a script")
if __name__ == "__main__": # true only when this file is run directly, not imported
main()Packages from the Python Package Index (PyPI) are installed with pip. Always use a virtual environment per project so packages do not clash between projects:
python3 -m venv .venv
source .venv/bin/activate
pip install requests
pip freeze > requirements.txtThe .venv folder is like node_modules and is not committed. Newer tools such as uv and Poetry manage environments and lock files, like pnpm.
How to say it in an interview
"In Python, __init__ is the constructor and self is passed explicitly. I use dunder methods like __repr__ and __eq__ to make classes work with built-in syntax, and dataclasses for simple data objects. Inheritance uses super().__init__. I raise and catch specific exceptions, use try/except/else/finally, and use 'with' for anything that must be cleaned up, like files. Each file is a module, I guard script code with if __name__ == '__main__', and use a virtual environment per project with pip or uv."
Key words
| Word | Meaning |
|---|---|
| __init__ | The constructor method |
| self | The current object, passed as the first parameter |
| Dunder method | A special method like __repr__ or __eq__ |
| Dataclass | A class that gets __init__, __repr__ and __eq__ written for it |
| with | Runs setup and guaranteed cleanup |
| Virtual environment | An isolated folder of packages for one project |
| pip / PyPI | Python's package installer / package registry |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.