← Learning Hub
Beginner

Classes and Objects

A class is a blueprint, and an object is a real thing made from it. __init__ runs when a new object is made, and self means "this object".

So far we've stored data (variables, lists, dictionaries) and actions (functions) separately. A class puts them together. A Product class says: every product has a name and a price (data), and can calculate a discount (action).

The class is like a form or a blueprint; each object is one filled-in copy. You write the class once and create as many objects as you like - one for every product in your shop. Each object keeps its own values, so changing one product's price doesn't affect another.

This style is called object-oriented programming (OOP). Big programs - games, websites, banking software - use it to keep code organised, because each class takes care of one kind of thing.

Example
You can edit this code.

Inheritance

A child class can reuse a parent class and change what it needs.

Inheritance means "is a kind of": a card payment is a kind of payment. The child class gets everything from the parent for free, and only changes (overrides) what's different. This avoids copying code, and lets you treat different objects the same way - the loop calls fee() on every payment without caring which type it is.

Example
You can edit this code.

Showing an object nicely

Example
You can edit this code.

Methods with double underscores, like __init__ and __str__, are special: Python calls them automatically at certain moments. __str__ decides what print(object) shows. Without it, you'd see something unhelpful like <__main__.Coupon object at 0x...>.

Key points
  • A class is a blueprint; objects are real things made from it.
  • __init__ sets up a new object; self means this object.
  • Inheritance lets a child class reuse and change a parent class.
  • __str__ controls how an object looks when printed.

📝 Test yourself

1. Which method runs when a new object is created?
2. What does self refer to?
3. Fill in the keyword that creates a class:
Product: