class Car: def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive(self): long_name = f"{self.year},{self.make},{self.model}" return long_name.title() def read_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can not roll back an odometer!") def increase(self,mile): self.odometer_reading += mile class Battery: def __init__(self): self.battery_size = 75 def describe_battery(self): print(f"This car has a {self.battery_size}-kWh size. ") def upgrade_battery(self): self.battery_size = 100 print(self.battery_size) def get_range(self): if self.battery_size == 75: range = 260 elif self.battery_size == 100: range = 315 print(f"This car can go about {range} miles on a full charge") class ElectricCar(Car): def __init__(self,make,model,year): super(ElectricCar, self).__init__(make,model,year) self.battery = Battery my_tesla = ElectricCar('tesla','model a ',2019) my_tesla.battery().describe_battery() my_tesla.battery().upgrade_battery() my_tesla.battery().describe_battery()我把Battery这个类赋给ElectricCar之后,最开始给Battery中的battery_size赋值是75,我想要通过在Battery中upgrade_battery这个函数去修改battery_size的值,在通过range让它表现出来,但是我发现每次调用upgrade_battery之后,再调用range或者describe_battery的时候,它还是调用的默认值75,这是为什么呢,在修改父类的时候就不会有这个问题,比如我修改odometer_reading的时候每次就都是会调用我修改完之后的值。 This car has a 75-kWh size. 100 This car has a 75-kWh size. |