python作业3.0

1、编写程序,创建基类Vehicle,其成员包括实例属性brand(品牌)和color(颜色),实例方法showInfo()用来输出实例属性brand和color的值;创建派生类Car,继承Vehicle类,新增实例属性seat(座位数),重写基类的实例方法showInfo ()输出所有实例属性的值。利用__init__()构造方法完成Vehicle和Car类的对象初始化工作,并编写测试代码。

class Vehicle:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color
    
    def showInfo(self):
        print(f"Brand: {self.brand}, Color: {self.color}")

class Car(Vehicle):
    def __init__(self, brand, color, seat):
        super().__init__(brand, color)
        self.seat = seat
    
    def showInfo(self):
        super().showInfo()
        print(f"Seat: {self.seat}")

if __name__ == "__main__":
    vehicle = Vehicle("Toyota", "Blue")
    vehicle.showInfo()

    car = Car("BMW", "Black", 5)
    car.showInfo()

2、创建一个名为Shape的父类,具有一个area方法。然后创建一个Rectangle子类,继承自Shape,并具有额外的width和height属性。该子类还应该具有一个perimeter方法来计算矩形的周长。

class Shape:
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height
    
    def perimeter(self):
        return 2 * (self.width + self.height)

if __name__ == "__main__":
    rectangle = Rectangle(5, 4)
    print("Area of rectangle:", rectangle.area())
    print("Perimeter of rectangle:", rectangle.perimeter())

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值