__init__ and attributes
Python · Unit 12: Classes and objects
- Full plan
- Python
- 10 exercises
Storing attributes one by one from the outside gets tiring, and it's easy to forget one.
If you write a function called __init__ inside the class, with two underscores on each side, Python runs it on its own every time you create an object. We'll get to self in a moment.
class Bulb:
def __init__(self):
print("New bulb")
a = Bulb()
b = Bulb()Prints
New bulb New bulb
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. Complete the code
Complete it so each book stores its title.
3. Multiple choice
With this class, when you write
p = Point(3, 4), what does__init__receive?4. Find the bug
This program should print 2 5. Which line has the error?
5. Predict the output
What does this code print?
6. Complete the code
Complete it so it prints: Ana got 9
7. Find the bug
This program should print Luna 2. Which line has the error?
8. Put the lines in order
A taxi charges 8 per kilometer. Put the lines in order so it prints the fare for a 15 km trip.
9. Write the code
Write the
__init__forMovieso it storestitleandyear. The lines below already use it and should print Coco 2009.10. Predict the output
maxwithkeyworks with objects too. 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.