Command Palette

Search for a command to run...

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

A Dog class with two objects

Press Run. Then add a third dog and call its methods. Notice that Rex's birthday does not change Bella.

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 Dog class with two objects
Sign in to run this example in your browser.

Expected output

Rex says Woof!
Bella says Woof!
Rex is now 4
Bella is still 5
Dog(name='Rex', age=4)
<class '__main__.Dog'>
False