题目
1、通过继承前面课程作业中定义的盒子(Box)类,实现可以相加的盒子类,并定义一个调用让盒子可以相加的函数。
2、通过鸭子类型定义一个杯子类,能够将其实例提供给上题中的函数,使得相加后得到一个容量为两个杯子类的实例容量之和的杯子类实例。
答案
1、
class Box: # Box类
instanceNum = 0 # 实例数
def __init__(self, length=0, width=0, height=0):
self.length = length # 长
self.width = width # 宽
self.height = height # 高
self.__volume = self.length * self.height * self.width # 体积
Box.instanceNum += 1
class NewBox(Box):
def __init__(self, length, width, height):
super().__init__(length, width, height)
self.__volume = self.length * self.width *self.height
def __add__(self, other):
newLength = self.length + other.length
newWidth = self.width + other.width
newHeight = self.height + other.height
return NewBox(newLength, newWidth, newHeight)
@property
def volume(self):
return self.__volume
def newbox_add(a,b):
return a + b
2、
# 杯子类
class Cup():
def __init__(self, volume):
self.__volume = volume
@property
def volume(self):
return self.__volume
def __add__(self, other):
return Cup(self.volume + other.volume)
def newbox_add(a,b):
return a + b
测试
1、
if __name__ == "__main__":
print(newbox_add(NewBox(1, 2, 3), NewBox(4, 5, 6)).volume) # 315
2、
if __name__ == "__main__":
cup1 = Cup(4)
cup2 = Cup(6)
cup3 = cup1 + cup2
print(cup3.volume) #10