开始使用免费开始使用

重载 +

可重载的不仅是比较运算符。Python 中的类可以为 +- 等算术运算符实现自定义功能。在本例中,您将练习为 Storage 类重载 + 运算符。

本练习是课程的一部分

Python 面向对象编程进阶

查看课程

练习说明

  • Storage 类定义一个魔术方法,用于重载 + 运算符。
  • 创建一个名为 total_storage 的新 Storage 对象,其 capacity 等于两个对象 capacity 的总和。
  • onboard_storageexternal_drive 相加以创建 total_storage 对象,并打印 total_storagecapacity

交互式实操练习

通过完成这段示例代码来试试这个练习。

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.____)
  
编辑并运行代码