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.
Este exercício faz parte do curso
Intermediate Object-Oriented Programming in Python
Instruções do exercício
- 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.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
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.____)