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