1、定义一个rain类的实象train1,定义一个car类的实例对象car1,定义一个truck类的实V象truck1,定义一个aircrah类的实例对象aircraft1,打印出所有实例对象的所有特性。2、对car类增加颜色(color)属性,并参考51.2节对颜色(color)属性进行数据封装。3、采用多重勇的方式,在现有类的基础上定义一个能像飞机一样飞行的小汽车类( aircraf-car )
时间: 2023-07-10 12:05:49 浏览: 89
train1_CIFAR数据集train1_
1.
```python
# 定义类Train
class Train:
def __init__(self, speed, length, weight):
self.speed = speed
self.length = length
self.weight = weight
# 定义类Car
class Car:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
# 定义类Truck
class Truck:
def __init__(self, weight_capacity, volume_capacity, fuel_type):
self.weight_capacity = weight_capacity
self.volume_capacity = volume_capacity
self.fuel_type = fuel_type
# 定义类Aircraft
class Aircraft:
def __init__(self, wingspan, length, weight):
self.wingspan = wingspan
self.length = length
self.weight = weight
# 实例化对象
train1 = Train(200, 1000, 5000)
car1 = Car("Tesla", "Model S", 100000)
truck1 = Truck(5000, 50, "diesel")
aircraft1 = Aircraft(30, 50, 10000)
# 打印对象属性
print("train1: speed={}, length={}, weight={}".format(train1.speed, train1.length, train1.weight))
print("car1: brand={}, model={}, price={}".format(car1.brand, car1.model, car1.price))
print("truck1: weight_capacity={}, volume_capacity={}, fuel_type={}".format(truck1.weight_capacity, truck1.volume_capacity, truck1.fuel_type))
print("aircraft1: wingspan={}, length={}, weight={}".format(aircraft1.wingspan, aircraft1.length, aircraft1.weight))
```
2.
```python
# 定义类Car
class Car:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.__color = 'unknown' # 默认颜色为未知
self.price = price
def get_color(self):
return self.__color
def set_color(self, color):
self.__color = color
# 实例化对象
car1 = Car("Tesla", "Model S", 100000)
# 打印对象属性
print("car1: brand={}, model={}, price={}, color={}".format(car1.brand, car1.model, car1.price, car1.get_color()))
# 修改颜色
car1.set_color('red')
# 打印对象属性
print("car1: brand={}, model={}, price={}, color={}".format(car1.brand, car1.model, car1.price, car1.get_color()))
```
3.
```python
# 定义类Aircraft
class Aircraft:
def __init__(self, wingspan, length, weight):
self.wingspan = wingspan
self.length = length
self.weight = weight
def fly(self):
print("I am flying!")
# 定义类AircraftCar,继承自Car和Aircraft
class AircraftCar(Car, Aircraft):
def __init__(self, brand, model, price, wingspan, length, weight):
Car.__init__(self, brand, model, price)
Aircraft.__init__(self, wingspan, length, weight)
# 实例化对象
aircraft_car1 = AircraftCar("Flying Car", "Model X", 200000, 50, 80, 5000)
# 打印对象属性
print("aircraft_car1: brand={}, model={}, price={}, wingspan={}, length={}, weight={}".format(aircraft_car1.brand, aircraft_car1.model, aircraft_car1.price, aircraft_car1.wingspan, aircraft_car1.length, aircraft_car1.weight))
# 调用fly方法
aircraft_car1.fly()
```
输出结果:
```
aircraft_car1: brand=Flying Car, model=Model X, price=200000, wingspan=50, length=80, weight=5000
I am flying!
```
阅读全文