Browser lab18 min+60 XP

Special methods

Teach your objects to print nicely, compare with == and work with len().

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

Special methods let print(), len() and == work with your objects.

Key words
print(card)card.__str__()[card, card]card.__repr__()a == ba.__eq__(b)len(p)p.__len__()you writePython calls
What you write, and the special method Python calls for you.

Python calls special "dunder" methods behind the scenes. __str__ decides what print(obj) shows. Without it you get something like <__main__.Card object at 0x...>, which is not very friendly.

__repr__ gives a developer-friendly description (shown when an object is inside a list). __eq__(self, other) decides what == means. __len__ lets len(obj) work.

Special methods make your own classes feel like Python's built-in types.

Real life linkPython knows how to add two numbers, and it can learn how to add two of your own objects. Special methods teach it how.
Example code
class Card:
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        return f"{self.rank} of {self.suit}"

    def __repr__(self):
        return f"Card({self.rank!r}, {self.suit!r})"

    def __eq__(self, other):
        return self.rank == other.rank and self.suit == other.suit

a = Card("Ace", "Spades")
b = Card("Ace", "Spades")
print(a)
print([a, Card("7", "Hearts")])
print(a == b)
TASK 2

Try it yourself

+10 XP

Give Playlist a __str__ that returns Road Trip (3 songs) and a __len__ that returns the number of songs.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

Which special method decides what print() shows for your object?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Money class

+20 XP

Write a class Money storing an amount in pence. __str__ shows pounds like £3.05, __eq__ compares amounts, and __add__(self, other) returns a new Money with the total. Test: Money(250) + Money(55) prints £3.05, and Money(100) == Money(100) prints True.

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.