CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Intermediate Object-Oriented Programming in Python

Afficher le cours

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.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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.____)
  
Modifier et exécuter le code