编写类时,并非要从空白开始。如果你要编写的类是另一个现成的类的特殊版本,可使用继承。一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类。子类继承了父类的所有属性和方法,同时好似定义自己的属性和方法。
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can`t roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading += miles
"""创建子类时,父类必须包含在当前文件中,且位于子类前面"""
"""定义子类时,必须在括号内指定父类的名字"""
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):#方法__init__接收创建Car实类所需的信息
"""初始化父类的属性"""
super().__init__(make,model,year)
"""super()是一个特殊函数,帮助Python将子类和父类联系起来"""
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
给子类定义属性和方法:让一个类进程另一个类后,可添加区分子类和父类所需的新属性和方法。对于ElectriCar类的特殊化程度并没有任何限制。模拟电动汽车时,你可以根据所需的准确程度添加任意数量的属性和方法。如果一个属性或者方法是任何汽车都有的,而不是电动汽车特有的,就应该将其加入到Car类而不是ElectricCar类中。
class Car():
--snip--
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):#方法__init__接收创建Car实类所需的信息
"""初始化父类的属性"""
super().__init__(make,model,year)
"""super()是一个特殊函数,帮助Python将子类和父类联系起来"""
self.battery_size = 70#添加新的属性
def describe_battery(self):
"""打印一条描述电瓶容量的信息"""
print("This car has a " + str(self.battery_size) +"-kwh battery.")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
重写父类的方法:对于父类的方法,只要它不符合子类模拟的实物的行为,都可以对其进行重写。为此,可在子类中定义一个这样的方法,即它与要重写的父类方法同名。这样,Python将不会考虑这个父类方法,而只关注你在子类中定义的相应方法。
假设Car类有一个名为fill_gas_tank的方法,它对全电动车来说毫无意义,因此可以重写。
class ElectricCar(Car):
--snip--
def fill_gas_tank(self):
"""电动车没有油箱"""
print("This car doesn`t need a gas tank!")
现在,如果有人对电动车调用方法fill_gas_tank(),Python将忽略Car类中的fill_gas_tank(),转而运行上述代码。
将实例用作属性:使用代码模拟实物时,你可能会发现自己给类添加的实类越来越多:属性和方法清单以及文件都越来越长。在这种情况下,可能需要将类的一部分作为一个独立的类提取出来
calss Car()
--snip--
class Battery():#新类没有继承任何类
"""一次模拟简单电动汽车点评的简单尝试"""
def __init__(self,battery_size=70):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-kwh battery")
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):#方法__init__接收创建Car实类所需的信息
"""初始化父类的属性"""
super().__init__(make,model,year)
self.battery = Battery()
"""添加了一个名为self.battery的属性。这行代码让Python创建一个新的Battery实例,并将该实例存储在属性self.battery中"""
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()