Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.1 — Classes and Objects
Python · Example 3 of 3

A realistic class: a shopping cart

Dogs are a toy. This is closer to real programs: each customer has their own cart (data) and the cart knows how to add items and total the bill (behaviour). Each cart keeps its own items list. Add a third customer and a method that counts items.

A class is a blueprint that describes what a kind of thing knows (its attributes) and what it can do (its methods); an object, also called an instance, is one real thing built from that blueprint. __init__ sets up each new object, and self is the name a method uses for the object it was called on.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a class Rectangle with attributes width and height, and methods area() and perimeter(). Print both for a 3 by 4 rectangle.

02

Write a class Counter with a count starting at 0, an add() method that increases it and returns self, and a reset() method. Add three times in a chain and print the count.

03

Write a class Book with title and pages, and a __repr__ that returns text like Book('Python', 300). Print a list of two books.

Explain it without notes

01

What is the difference between a class and an object?

02

What does __init__ do, and when is it called?

03

What is self, and why do methods take it explicitly?

04

What does it mean that "everything is an object" in Python?

A realistic class: a shopping cart
Sign in to run this example in your browser.

Expected output

ShoppingCart('Asha', 2 items) total: 75
ShoppingCart('Ben', 1 items) total: 500
{'name': 'pen', 'price': 10, 'quantity': 3}