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())