麦子学院——Python面型对象编程(P11鸭子类型与多态)

题目

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值