Editor

Refactor Methods to Operators

Advanced · Refactor · from Python Operator Overloading: Make Classes Work with +, -, ==

From the lesson: Python Operator Overloading: Make Classes Work with +, -, ==

The + operator means different things in different contexts. 3 + 5 gives you 8. 'hello' + ' world' gives you 'hello world'. [1, 2] + [3, 4] gives you [1, 2, 3, 4]. Same symbol, completely different behavior.

Read the lesson

Refactor this Wallet class to use operator overloading. Replace add_money(amount) with __iadd__, subtract_money(amount) with __isub__, and equals(other) with __eq__. Add __repr__ returning 'Wallet(<balance>)'. Then create Wallet(100), add 50, subtract 30, print the wallet, and print whether it equals Wallet(120).

class Wallet:
def __init__(self, balance=0):
self.balance = balance
def add_money(self, amount):
self.balance += amount
def subtract_money(self, amount):
self.balance -= amount
def equals(self, other):
return self.balance == other.balance
# Refactor the class above, then test it

More Operator Overloading exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz