3.继承
如果你要编写的类是一个现成类的特殊版本,可使用继承,一个类继承另一个类,会自动获得另一个类的所有属性和方法;原有的类称为父类,新类称为子类。子类继承父类的所有属性和方法,同时能够定义自己的属性和方法。
3.1 子类的方法 init()
创建子类实例,首要任务是给父类的所有属性赋值。
下面创建一个汽车的特殊子类—电动汽车,electric_car
##以下为之前创建好的Car类
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):
"""打印一条指出汽车里程的消息"""
print("This car has " + str(self.odometer_reading) + " miles on it")
##----------------------------------------------------------------------------
##以下为创建子类
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
上半部分是父类代码。创建子类时,父类要被包含在当前文件夹内,且位于子类前。
下半部分是子类代码。定义子类时,必须在括号内指定父类的名称。方法__init__()接受创建Car实例所需的信息。
第27行处的super()是一个特殊函数,帮助python将父类和子类关联起来。这行代码让ElectricCar实例包含父类的所有属性。父类也被称为超类(superclass)。
在测试中,ElectricCar实例的行为和Car实例一样。
3.2 给子类定义属性和方法
下面代码添加了一个电动汽车特有的属性,以及描述该属性的方法。
添加了新属性self.battery_size和新方法describe_battery(self)
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性,再初始化电动汽车的特有属性"""
super().__init__(make, model, year)
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()
运行结果
2016 Tesla Model S
This car has a 70-kWh battery.
对子类的特殊化程度没有限制,你可以根据需要的描述准确程度设计任意数量的属性和方法。如果某一个属性或方法是所有汽车都有的,那么这个属性或方法应该放到父类中。子类只包含特有的属性和行为。
3.3 重写父类的方法
对于父类的方法,只要它不符合子类模拟的实物的行为,都可以对其进行重写。
方法:可在子类中定义一个方法,这个方法的名字和父类中方法的名字相同,这样Python运行是会略过父类的这个方法,运行子类方法。
如:
def describe_gas_tank(self):
"""打印一条描述油箱容量的消息"""
print("This car doesn‘t need a gas tank")
3.4 将实例用作属性
当子类中的新属性和方法足够多到创建另一个子类时,我们可以将这些属性和方法提取出来创建新子类。
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):
"""初始化父类的属性,再初始化电动汽车的特有属性"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
定义了一个Battery类,注意在ElectricCar类中加入self.battery = Battery(),这样传建一个新的Battery实例,并将该实例存储到属性self.battery中。每当方法__init__()被调用时,都将执行该操作