Get startedGet started for free

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

View Course

Exercise instructions

  • Define a magic method to overload the + operator for the Storage class.
  • Create a new Storage object called total_storage with a capacity that equals the combined capacity of both objects.
  • Add the onboard_storage and external_drive objects to create a total_storage object, and print the capacity of total_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.____)
  
Edit and Run Code