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
Instructions
- Define a magic method to overload the
+operator for theStorageclass. - Create a new
Storageobject calledtotal_storagewith acapacitythat equals the combinedcapacityof both objects. - Add the
onboard_storageandexternal_driveobjects to create atotal_storageobject, and print thecapacityoftotal_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.____)