ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
如果你要编写的类是另一个现成类的特殊版本,可使用继承。一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。 ## 9.3.1 子类的方法_init_() 创建子类的实例时, Python首先需要完成的任务是给父类的所有属性赋值。为此,子类的方法_init_()需要父类施以援手。 ``` from car import Car #Car是父类,ElectricCar是子类 class ElectricCar(Car): 初始化子类实例,需要先对父类属性赋值 def __init__(self, manufacturer, model, year): super().__init__(manufacturer, model, year) self.battery = Battery() ``` 创建子类时,父类必须包含在当前文件中,且位于子类前面。 定义子类时,必须在括号内指定父类的名称。 ## 9.3.3 给子类定义属性和方法 添加battery_size属性和describe_battery(self)方法 ![](https://img.kancloud.cn/c3/6e/c36e2d292eaaf1867011ab5de5b9b7ab_692x440.png) ## 9.3.4 重写父类的fill_gas_tank()方法 在子类中定义一个这样的方法,即它与要重写的父类方法同名。这样, Python将不会考虑这个父类方法,而只关注你在子类中定义的相应方法。 假设Car类有一个名为fill_gas_tank()的方法,它对全电动汽车来说毫无意义,因此你可能想重写它。下面演示了一种重写方式: ![](https://img.kancloud.cn/61/e4/61e459b59ad6bc0a9a36b3d0bd5e5ab5_438x127.png) ## 9.3.5 将实例用作属性 不断给ElectricCar类添加细节时,我们可能会发现其中包含很多专门针对汽车电瓶 的属性和方法。在这种情况下,我们可将这些属性和方法提取出来,放到另一个名为Battery的类中,并将一个Battery实例用作ElectricCar类的一个属性: ``` from car import Car class Battery(): """A simple attempt to model a battery for an electric car.""" def __init__(self, battery_size=60): """Initialize the batteery's attributes.""" self.battery_size = battery_size def describe_battery(self): """Print a statement describing the battery size.""" print("This car has a " + str(self.battery_size) + "-kWh battery.") def get_range(self): """Print a statement about the range this battery provides.""" if self.battery_size == 60: range = 140 elif self.battery_size == 85: range = 185 message = "This car can go approximately " + str(range) message += " miles on a full charge." print(message) class ElectricCar(Car): """Models aspects of a car, specific to electric vehicles.""" def __init__(self, manufacturer, model, year): super().__init__(manufacturer, model, year) self.battery = Battery() ```