Why classes?
Imagine a game with many players. Each has a name, health points and an inventory, and each can take damage or pick up items. A class is the blueprint for "a player"; each actual player is an object (an instance) made from that blueprint, with its own data.
Your first class
class Player:
def __init__(self, name, health=100):
self.name = name
self.health = health
self.items = []
def take_damage(self, amount):
self.health = max(0, self.health - amount)
def pick_up(self, item):
self.items.append(item)
def is_alive(self):
return self.health > 0
hero = Player("Ana")
hero.take_damage(30)
hero.pick_up("map")
print(hero.name, hero.health, hero.items) # Ana 70 ['map']
__init__runs when you create an object and sets its starting data.selfis the object itself;self.healthis that player's own health.- Functions inside a class are called methods.
Printing objects nicely
class Player:
def __init__(self, name, health=100):
self.name = name
self.health = health
def __str__(self):
return f"{self.name} ({self.health} HP)"
print(Player("Ana")) # Ana (100 HP)
Without __str__, printing an object shows something like <__main__.Player object at 0x...>.
Example: a bank account
class BankAccount:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("Not enough money")
self.balance -= amount
account = BankAccount("Besa")
account.deposit(50)
account.withdraw(20)
print(account.balance) # 30
try:
account.withdraw(100)
except ValueError as error:
print("Refused:", error) # Refused: Not enough money
The methods protect the rules: the balance can only change through deposit and withdraw, which check the amounts. Keeping data and its rules together is the main benefit of classes.
A first look at inheritance
class SavingsAccount(BankAccount):
def add_interest(self, rate):
self.balance += self.balance * rate
savings = SavingsAccount("Dren")
savings.deposit(200)
savings.add_interest(0.05)
print(savings.balance) # 210.0
SavingsAccount gets every method of BankAccount and adds its own. Use inheritance when one thing truly is a special kind of another.
Try it yourself
In Unays Code, write a Library class with methods to add a book, lend it to someone and return it, refusing to lend a book that is already out.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].