重载 +
可重载的不仅是比较运算符。Python 中的类可以为 +、- 等算术运算符实现自定义功能。在本例中,您将练习为 Storage 类重载 + 运算符。
本练习是课程的一部分
Python 面向对象编程进阶
练习说明
- 为
Storage类定义一个魔术方法,用于重载+运算符。 - 创建一个名为
total_storage的新Storage对象,其capacity等于两个对象capacity的总和。 - 将
onboard_storage和external_drive相加以创建total_storage对象,并打印total_storage的capacity。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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.____)