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.
Write a class Rectangle with attributes width and height, and methods area() and perimeter(). Print both for a 3 by 4 rectangle.
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.
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
What is the difference between a class and an object?
What does __init__ do, and when is it called?
What is self, and why do methods take it explicitly?
What does it mean that "everything is an object" in Python?
Expected output
ShoppingCart('Asha', 2 items) total: 75
ShoppingCart('Ben', 1 items) total: 500
{'name': 'pen', 'price': 10, 'quantity': 3}