Skip to the content

__init__ and attributes

Python · Unit 12: Classes and objects

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. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Complete it so each book stores its title.

  3. 3. Multiple choice

    With this class, when you write p = Point(3, 4), what does __init__ receive?

  4. 4. Find the bug

    This program should print 2 5. Which line has the error?

  5. 5. Predict the output

    What does this code print?

  6. 6. Complete the code

    Complete it so it prints: Ana got 9

  7. 7. Find the bug

    This program should print Luna 2. Which line has the error?

  8. 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. 9. Write the code

    Write the __init__ for Movie so it stores title and year. The lines below already use it and should print Coco 2009.

  10. 10. Predict the output

    max with key works with objects too. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →