Consider the following Python class that overloads the + operator. What will be the output of the code below?
class Number: def __init__(self, value): self.value = value def __add__(self, other): return Number(self.value + other.value) def __str__(self): return str(self.value) n1 = Number(5) n2 = Number(10) result = n1 + n2 print(result)
Look at how the __add__ method returns a new Number object and how __str__ controls printing.
The __add__ method returns a new Number object with the sum of the two values. The print calls __str__, which returns the string of the summed value, so it prints 15.
What is the output of this code that overloads the - operator?
class Point: def __init__(self, x, y): self.x = x self.y = y def __sub__(self, other): return Point(self.x - other.x, self.y - other.y) def __repr__(self): return f"Point({self.x}, {self.y})" p1 = Point(10, 5) p2 = Point(3, 2) print(p1 - p2)
Check how the __sub__ method calculates the difference of coordinates.
The __sub__ method returns a new Point with each coordinate subtracted. So (10-3, 5-2) = (7, 3).
What will this code print? The * operator is overloaded to return an integer.
class Vector: def __init__(self, x, y): self.x = x self.y = y def __mul__(self, other): return self.x * other.x + self.y * other.y v1 = Vector(2, 3) v2 = Vector(4, 5) print(v1 * v2)
The * operator here calculates the dot product of two vectors.
The dot product is (2*4) + (3*5) = 8 + 15 = 23, so the code prints 23.
What is the output of this code that overloads the += operator?
class Counter: def __init__(self, count=0): self.count = count def __iadd__(self, other): self.count += other.count return self def __str__(self): return str(self.count) c1 = Counter(5) c2 = Counter(10) c1 += c2 print(c1)
The __iadd__ method modifies the object in place and returns it.
The += operator calls __iadd__, which adds the counts and returns the updated object. Printing calls __str__, so it prints 15.
Given this class that only overloads __add__, what happens if you try to subtract two objects?
class MyNum:
def __init__(self, val):
self.val = val
def __add__(self, other):
return MyNum(self.val + other.val)
x = MyNum(5)
y = MyNum(3)
z = x - yCheck what happens if an operator method is not defined for a class.
Since __sub__ is not defined, Python raises a TypeError saying the operator is unsupported for the given types.