如果你要編寫的類是另一個現成類的特殊版本,可使用繼承。一個類繼承另一個類時,它將自動獲得另一個類的所有屬性和方法;原有的類稱為父類,而新類稱為子類。子類繼承了其父類的所有屬性和方法,同時還可以定義自己的屬性和方法。
## 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)方法

## 9.3.4 重寫父類的fill_gas_tank()方法
在子類中定義一個這樣的方法,即它與要重寫的父類方法同名。這樣, Python將不會考慮這個父類方法,而只關注你在子類中定義的相應方法。
假設Car類有一個名為fill_gas_tank()的方法,它對全電動汽車來說毫無意義,因此你可能想重寫它。下面演示了一種重寫方式:

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