// python · beginner
Python Classes and Objects: A Beginner's Guide to OOP
Learn object-oriented programming in Python. Create classes, use __init__ and self, write methods, add a readable __str__, and reuse code with inheritance.
As programs grow, you’ll find data and the functions that work on it start to belong together. A game has players, each with a name, health and score, plus actions such as take damage or level up. Classes let you bundle that data and those actions into one neat package. This style is called object-oriented programming (OOP), and it’s used in most large programs.
Classes and objects
- A class is a blueprint: it describes what something has and what it can do.
- An object (or instance) is one thing built from that blueprint.
One Dog class can produce many dog objects, each with its own name and age, just as one cake recipe produces many cakes.
You’ve been using objects all along: every string, list and dictionary is an object, which is why they have methods like "hi".upper() and scores.append(5).
Your first class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
rex = Dog("Rex", 3)
bella = Dog("Bella", 5)
rex.bark() # Rex says woof!
print(bella.age) # 5
Let’s take it apart:
class Dog:starts the class. Class names use CapitalisedWords by convention.__init__is a special method that runs automatically when you create an object. It sets up the object’s starting data. (The name has two underscores on each side.)selfmeans “this particular object”.self.name = namestores the name inside the object, as an attribute.barkis a method: a function that belongs to the class. It usesself.nameto find this dog’s name.Dog("Rex", 3)creates an object. Python passes the new object asselffor you, so you only give the other arguments.
Why self matters
Every method’s first parameter is self, and you must use it to reach the object’s attributes:
class Counter:
def __init__(self):
self.count = 0
def increase(self):
self.count += 1 # 'count += 1' on its own would be an error
a = Counter()
b = Counter()
a.increase()
a.increase()
b.increase()
print(a.count, b.count) # 2 1
Each object keeps its own attributes: increasing a doesn’t affect b.
Methods that change and return data
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds")
return False
self.balance -= amount
return True
account = BankAccount("Ava", 50)
account.deposit(25)
account.withdraw(100) # Insufficient funds
print(account.balance) # 75
Methods are the right place for rules like “you can’t withdraw more than you have”. Code that uses the class doesn’t need to remember them; the object enforces them itself. The raise line is explained in the try and except guide.
Making objects print nicely with __str__
Printing an object normally shows something unhelpful like <__main__.BankAccount object at 0x7f...>. Add a __str__ method to control what print shows:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
book = Book("Dracula", "Bram Stoker")
print(book) # Dracula by Bram Stoker
__str__ must return a string, not print it.
Inheritance: building on another class
Inheritance lets a new class start with everything another class has, then add or change things. The original is the parent (or base) class; the new one is the child:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
def describe(self):
return f"{self.name} says {self.speak()}"
class Cat(Animal):
def speak(self):
return "Meow"
class Cow(Animal):
def speak(self):
return "Moo"
for pet in [Cat("Tom"), Cow("Daisy"), Animal("Mystery")]:
print(pet.describe())
Tom says Meow
Daisy says Moo
Mystery says ...
Cat(Animal) means “a Cat is a kind of Animal”. Cat gets __init__ and describe for free, and overrides speak with its own version. When describe calls self.speak(), Python uses the version belonging to that object’s class.
Extending the parent’s __init__ with super()
If a child class needs extra attributes, call the parent’s __init__ with super() so you don’t repeat its code:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # let Animal set up the name
self.breed = breed
d = Dog("Rex", "Collie")
print(d.name, d.breed) # Rex Collie
When should you use a class?
Classes are useful when you have several things of the same kind, each with its own data and behaviour: players, accounts, shapes, enemies, products. For a short script that just does one job, plain functions are often simpler, and that’s fine. You don’t have to use classes everywhere.
Mini project: a tiny RPG battle
import random
class Character:
def __init__(self, name, health, power):
self.name = name
self.health = health
self.power = power
def is_alive(self):
return self.health > 0
def attack(self, other):
damage = random.randint(1, self.power)
other.health = max(0, other.health - damage)
print(f"{self.name} hits {other.name} for {damage}. "
f"{other.name} has {other.health} HP left.")
def __str__(self):
return f"{self.name} ({self.health} HP)"
hero = Character("Hero", 30, 8)
goblin = Character("Goblin", 25, 6)
while hero.is_alive() and goblin.is_alive():
hero.attack(goblin)
if goblin.is_alive():
goblin.attack(hero)
winner = hero if hero.is_alive() else goblin
print(f"\n{winner} wins!")
Each character keeps its own health, and the same attack method works for both. Challenge: create a Healer(Character) child class with a heal(self) method that restores some health, and let the hero use it when their health is low.
Key points
- A class is a blueprint; an object is one thing made from it.
__init__sets up a new object;selfrefers to that object.- Attributes store data (
self.name); methods are functions inside the class. __str__controls how an object prints.- Inheritance (
class Cat(Animal):) reuses a parent class;super()calls the parent’s version.
Put it all together in a real program with the To-Do List App project. As an extra challenge, rewrite it so each task is an object.