Predict the Operator Output
Intermediate · Predict the output · 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 lessonRead the code carefully and predict exactly what gets printed. Think about which magic methods are called for each operation.
class Num:
def __init__(self, val):
self.val = val
def __add__(self, other):
return Num(self.val + other.val)
def __eq__(self, other):
return self.val == other.val
def __repr__(self):
return str(self.val)
a = Num(10)
b = Num(20)
c = a + b
print(c)
print(a + b == Num(30))
print(a + b == Num(99))
More Operator Overloading exercises
- Add Two Points TogetherBeginner
- Scale a Vector with MultiplicationIntermediate
- Fix the Broken __iadd__Intermediate
- Build a Fraction ClassAdvanced
- Refactor Methods to OperatorsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz