Special methods
Teach your objects to print nicely, compare with == and work with len().
Code runs right here in your browser. Nothing to install.
Learn it
Special methods let print(), len() and == work with your objects.
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.
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)
Try it yourself
+10 XPGive 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.
Capture the flag
+10 XPWhich 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.
Money class
+20 XPWrite 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.