Skip to the content

super()

Python · Unit 13: Inheritance

If the child writes its own __init__, it replaces the parent's: the parent's no longer runs, and whatever it used to store doesn't get stored.

class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, breed):
        self.breed = breed

d = Dog("pug")
print(d.breed)
try:
    print(d.name)
except AttributeError:
    print("It has no name")

Prints

pug
It has no name

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. Multiple choice

    With this code, print(d.name) gives an AttributeError. Why?

  3. 3. Complete the code

    Complete it so the dog also stores its name.

  4. 4. Complete the code

    Complete it so it prints: Valeria 3B

  5. 5. Predict the output

    What does this code print?

  6. 6. Find the bug

    This program should print Luis Math. Which line has the bug?

  7. 7. Multiple choice

    Instead of super().__init__(name), the child could write self.name = name again. Why is super() better?

  8. 8. Put the lines in order

    Bread on sale costs 30 minus a 5 discount. Put the lines in order so it prints 25.

  9. 9. Predict the output

    What does this code print?

  10. 10. Write the code

    Write Student's __init__: it takes name and sch, stores the name with super() and stores the school in self.school. It should print Leo North High.

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 →