Skip to the content

Special methods

Python · Unit 14: Modern classes

You've already seen that Python calls __init__, __str__ and __eq__ on its own. There is one for each thing you want your object to know how to do.

__len__ answers len(object) and has to return a whole number.

class Backpack:
    def __init__(self):
        self.things = []

    def put(self, t):
        self.things.append(t)

    def __len__(self):
        return len(self.things)

b = Backpack()
b.put("book")
b.put("pen")
print(len(b))

Prints

2

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. Complete the code

    Complete it so len(d) says how many cards there are.

  2. 2. Predict the output

    The shipment carries two boxes, one with 2 pieces and one with 3. What does it print?

  3. 3. Find the bug

    The deck has 3 cards, so it should print 3. Which line has the error?

  4. 4. Predict the output

    The group holds students, but the search is by name. What does it print?

  5. 5. Multiple choice

    A route with 4 stops gives len(route) equal to 3. What is it counting?

  6. 6. Predict the output

    What does this code print?

  7. 7. Find the bug

    Adding the two payments should print Payment(amount=50). Which line has the error?

  8. 8. Complete the code

    Complete it so it prints: Bag(kilos=8)

  9. 9. Put the lines in order

    Put the lines in order so it prints: 2 True

  10. 10. Predict the output

    Two boxes are put together into a third one. 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 →