Class attributes
Python · Unit 12: Classes and objects
- Full plan
- Python
- 10 exercises
A variable written straight inside the class, outside the methods, is a class attribute. There's only one, and every object shares it.
You can read it from any object or from the class itself.
class Taxi:
wheels = 4
def __init__(self, plate):
self.plate = plate
a = Taxi("ABC-12")
b = Taxi("XYZ-98")
print(a.wheels, b.wheels)
print(Taxi.wheels)Prints
4 4 4
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Complete the code
Complete it to calculate the circle's area.
4. Predict the output
What does this code print?
5. Multiple choice
In a
Studentclass, which data should be a class attribute?6. Find the bug
This program should print 2, the visits created. Which line has the error?
7. Predict the output
What does this code print?
8. Find the bug
Each team should have its own list of members. Ana joined red, so blue should print []. Which line has the error?
9. Put the lines in order
Put the lines in order so each order takes a number, starting at 1. It should print the second order's number.
10. Predict the output
Follow each bulb. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.