Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.2 — Instance vs Class Attributes
Python · Example 1 of 2

Lookup order and hiding

Predict each printed line before you run. Then change Dog.species at the end and see which dogs change.

Data can live on each object (instance attributes) or once on the class (class attributes). When you read obj.name, Python looks on the object first, then on its class, which explains shared defaults, the shared-list bug and why assigning through an instance never changes the class.

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 Student with a class attribute school = "Hectal High" and an instance attribute name. Create two students and print their schools, then change the school for all students in one line.

02

Write a class Ticket that counts how many tickets have been created, using a class attribute, and gives each ticket the next number as its number. Create three and print the numbers and the total.

03

The class below shares one list between all carts. Fix it so each cart has its own: class Cart: with items = [] and a method add(self, x) that appends.

Explain it without notes

01

What is the difference between an instance attribute and a class attribute?

02

In what order does Python look for obj.attr, and what does that mean for assignment?

03

Why is items = [] in a class body usually a bug?

04

Why does self.count += 1 not update a class-level counter?

Lookup order and hiding
Sign in to run this example in your browser.

Expected output

Canis familiaris Canis familiaris
Dogs made: 2
['name']
False
Rex's own
Canis familiaris
Canis familiaris
['name', 'species']
Canis familiaris