Overloading +
Comparison operators aren't the only operators that can be overloaded. Classes in Python can implement custom functionality for arithmetic operators such as +
and -
. In this example, you'll practice overloading the +
operator for a Storage
class.
This exercise is part of the course
Intermediate Object-Oriented Programming in Python
Exercise instructions
- Define a magic method to overload the
+
operator for theStorage
class. - Create a new
Storage
object calledtotal_storage
with acapacity
that equals the combinedcapacity
of both objects. - Add the
onboard_storage
andexternal_drive
objects to create atotal_storage
object, and print thecapacity
oftotal_storage
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
class Storage:
def __init__(self, capacity):
self.capacity = capacity
def ____(____, ____): # Overload the + operator
# Create a Storage object with the sum of capacity
return ____(self.____ + other.____)
onboard_storage = Storage(128)
external_drive = Storage(64)
# Add the two Storage objects, show the total capacity
total_storage = ____ + ____
print(total_storage.____)