Python初级 作业3

 1

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("品牌:", self.brand)
        print("颜色:", self.color)


class Car(Vehicle):
    def __init__(self, brand, color,seat):
        super().__init__(brand, color)
        self.seat = seat

    def showInfo(self):
        super().showInfo()
        print("座位数:", self.seat)
v=Vehicle("大众",'黑色')
c=Car("小米","黄色",5)
print(c.color)
print(c.seat)
print(c.brand)
print(v.color)

结果:

E:\Python\python.exe E:\学习笔记\Python\4.21\作业.py 
黄色
5
小米
黑色

 2

写法1、

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

class Shape:
    def area(self):
        pass
class Rectangle(Shape):
    def __init__(self, w,h):
        self.width = w
        self.height = h

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)
r=Rectangle(3,4)
s=Shape()
print(f"面积为{r.area()}")
print(f"周长为{r.perimeter()}")

 结果:

E:\Python\python.exe E:\学习笔记\Python\4.21\作业.py 
面积为12
周长为14

写法2、

class Shape:
    def area(self,w,h):
        return w*h
class Rectangle(Shape):
    def __init__(self, w,h):
        self.width = w
        self.height = h

    def area(self):
        # return self.width * self.height
        return(super().area(self.width,self.height))

    def perimeter(self):
        return 2 * (self.width + self.height)
r=Rectangle(3,4)
s=Shape()
print(f"面积为{r.area()}")
print(f"周长为{r.perimeter()}")

 

 结果:

E:\Python\python.exe E:\学习笔记\Python\4.21\作业.py 
面积为12
周长为14

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值