Topic 63 of 64
class
Overview
Classes define blueprints for objects that combine data (attributes) and behavior (methods). Python's class system supports OOP with inheritance, encapsulation, and polymorphism — used in every non-trivial Python application.
Syntax
python
class Dog:
# Class attribute (shared by all instances)
species = "Canis familiaris"
# Constructor (instance initialization)
def __init__(self, name: str, age: int) -> None:
self.name = name # instance attribute
self.age = age
# Instance method
def bark(self) -> str:
return f"{self.name} says: Woof!"
# String representation
def __repr__(self) -> str:
return f"Dog(name={self.name!r}, age={self.age})"
d = Dog("Rex", 3)
d.bark() # "Rex says: Woof!"Common Pitfalls
- Forgetting 'self' as the first parameter of instance methods is a very common beginner error — causes TypeError.
- Class attributes are shared across all instances — if mutable (like a list), all instances share it. Use instance attributes in __init__ instead.
- Interview tip: The @property decorator lets you expose _balance as a read-only attribute without explicit getter methods — more Pythonic than get_balance().
Real-World Example
A BankAccount class with deposit, withdraw, and balance
example
python
class BankAccount:
def __init__(self, owner: str, initial_balance: float = 0.0) -> None:
self.owner = owner
self._balance = initial_balance # _ convention = "private"
def deposit(self, amount: float) -> None:
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def withdraw(self, amount: float) -> None:
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
@property
def balance(self) -> float:
return self._balance
def __repr__(self) -> str:
return f"BankAccount(owner={self.owner!r}, balance={self._balance:.2f})"
acc = BankAccount("Alice", 100.0)
acc.deposit(50.0)
acc.withdraw(30.0)
print(acc.balance) # 120.0