Special Methods

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — What are Special Methods?

You already know `__init__` and `__str__`. These are called special methods (or dunder methods — double underscore). Python has many more! They let your objects work with operators like `+`, `==`, `<`, and even `len()`.

For example, when you write `len([1,2,3])`, Python actually calls the list's `__len__` method. Let's make our objects work the same way!

class Team: def __init__(self, members): self.members = members def __len__(self): return len(self.members) team = Team(["Aquachu", "Pyrochu", "Florachu"]) print(len(team))

By defining `__len__`, we can use `len()` on our own objects! Python translates `len(team)` into `team.__len__()`.

Exercise 2 — __eq__ — Equality

By default, `==` checks if two objects are the exact same object in memory, not if they have the same data. `__eq__` lets you define what "equal" means for your class.

class Codemon: def __init__(self, name, level): self.name = name self.level = level def __eq__(self, other): return self.name == other.name a = Codemon("Aquachu", 10) b = Codemon("Aquachu", 20) c = Codemon("Pyrochu", 10) print(a == b) print(a == c)

Now `==` checks if two Codémon have the same name, regardless of level. You decide what "equal" means!

Exercise 3 — __eq__ Behavior

What is printed?

class Codemon: def __init__(self, name, level): self.name = name self.level = level def __eq__(self, other): return self.level == other.level a = Codemon("Aquachu", 10) b = Codemon("Pyrochu", 10) print(a == b)
Options
• True
• False
• Error
• None

Hint : This `__eq__` compares levels, not names. Do both Codémon have the same level?

Exercise 4 — __lt__ — Less Than

`__lt__` defines the `<` operator. (lt = less than). This also makes `sorted()` work on your objects!

class Codemon: def __init__(self, name, level): self.name = name self.level = level def __lt__(self, other): return self.level < other.level def __str__(self): return f"{self.name} (Lv.{self.level})" team = [Codemon("Pyrochu", 25), Codemon("Aquachu", 10), Codemon("Florachu", 15)] team.sort() for myCdm in team: print(myCdm)

By defining `__lt__`, Python can sort our Codémon by level! `sorted()` and `.sort()` both use `<` under the hood.

Exercise 5 — Define __len__

Complete the `__len__` method so `len(team)` returns the number of Codémon.

Hint : The special method for `len()` has double underscores around "len". It returns the count of the internal list.

Exercise 6 — __add__ — The + Operator

`__add__` defines what `+` does for your objects. You can make it do anything — merge teams, combine stats, etc.

class Team: def __init__(self, members): self.members = members def __add__(self, other): return Team(self.members + other.members) def __str__(self): return ", ".join(self.members) team1 = Team(["Aquachu", "Pyrochu"]) team2 = Team(["Florachu", "Zap"]) combined = team1 + team2 print(combined)

`team1 + team2` calls `team1.__add__(team2)`. It creates a new Team with all members combined!

Exercise 7 — Define __eq__

Complete `__eq__` so two Codémon are equal if they have the same name and level.

Hint : Both the name AND the level must match for equality.

Exercise 8 — __add__ Result

What is printed?

class Team: def __init__(self, members): self.members = members def __add__(self, other): return Team(self.members + other.members) def __len__(self): return len(self.members) a = Team(["Aquachu", "Pyrochu"]) b = Team(["Florachu"]) c = a + b print(len(c))
Options
• 2
• 3
• 1
• Error

Hint : `+` combines both teams' members into one new team. Count all members.

Exercise 9 — Special Methods

Match each special method with what it enables.

Items to match
• `__len__`
• `__eq__`
• `__lt__`
• `__add__`
• `__str__`
Definitions
• `len(obj)` — get length
• `obj == other` — equality check
• `obj < other` — less than
• `obj + other` — addition
• `print(obj)` — string display

Exercise 10 — Sort by Level

Complete `__lt__` to sort Codémon by level.

Hint : "Less than" uses `<`. The dunder method is `__lt__`.

Exercise 11 — Full-featured Team Class

Create a `Team` class with these special methods: 1. `__init__` with a `name` and `members` list 2. `__len__` — returns number of members 3. `__add__` — merges two teams (use the first team's name) 4. `__eq__` — two teams are equal if they have the same members 5. `__str__` — returns `"TeamName: member1, member2"` 6. Test all 4 operations

Starter code
class Team: # __init__ # __len__ # __add__ # __eq__ # __str__ # Test all operations
Back to the course