·一个类继承另一个类时,自动获取另一个类的所有属性和方法;原有的类为父类,新类称为子类。子类继承父类的所有属性和方法,同时还可定义自己的属性和方法。
9.3.1 子类的方法 __inint__()
创建electric_car继承前面的Car类
class ElectricCar(Car): # 定义子类,需在括号里指定父类名称
"""电动汽车的独特之处"""
def __init__(self,make, model, year):
"""初始化父类属性"""
super().__init__(make, model, year) # 调用父类的方法__init__,让ElectricCar包含父类的所有属性
my_electric_car = ElectricCar('bmw', 'mosel s', 2016)
my_electric_car.get_descriptive_name()
9.3.2 Python2.7中的继承
1.函数super()需要两个实参:子类名和对象self。
2.在定义父类时在括号内指定object。
class Car(object):
def __init__(self,make, model, year):
--snip--
class ElectricCar(Car):
def __init__(self, make, model, year):
super(ElectricCar, self).__init__(make, model, year)
--snip--
9.3.3 给子类定义属性和方法
class ElectricCar(Car): # 定义子类,需在括号里指定父类名称
"""电动汽车的独特之处"""
def __init__(self,make, model, year):
"""
初始化父类属性
再初始化电动汽车特有的属性
"""
super().__init__(make, model, year) # 调用父类的方法__init__,让ElectricCar包含弗雷的所有属性
self.battery_size = 70
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-kwh battery")
my_electric_car = ElectricCar('bmw', 'mosel s', 2016)
my_electric_car.get_descriptive_name()
my_electric_car.describe_battery()
9.3.4 重写父类的方法
在子类中定义一个与需要重写的父类重名的方法,这样Python会忽略父类中的该方法,使用子类中的。
9.3.5 将实例用作属性
增加Battery()类,并添加相关方法
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year): # 注意__inint__下划线是左右两边各两个,若出错会报出takes no arguments的错误
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
# 添加odometer_reading属性,使其初始值为0
self.odometer_reading = 20
def get_descriptive_name(self):
"""返回整洁的描述信息"""
long_name = str(self.year) + " " + self.make + ' ' + self.model
print(long_name.title())
def update_odometer(self, mileage):
"""将里程表读数设置为指定的值"""
# self.odometer_reading = mileage
"""
将里程表读数设置为指定的值
禁止将里程表读数往回调
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer !")
def increment_odometer(self, miles):
"""
将里程表读数增加指定的量
禁止增加量为负数
"""
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't add negative number on odometer !")
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print("This car has " + str(self.odometer_reading) + " miles on it.")
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")
def get_range(self):
"""打印一条消息,指出电瓶车的续航里程"""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge"
print(message)
class ElectricCar(Car): # 定义子类,需在括号里指定父类名称
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""
初始化父类属性
再初始化电动汽车特有的属性
"""
super().__init__(make, model, year) # 调用父类的方法__init__,让ElectricCar包含弗雷的所有属性
self.battery = Battery()
my_electric_car = ElectricCar('bmw', 'model s', 2016)
my_electric_car.get_descriptive_name()
my_electric_car.battery.describe_battery()
my_electric_car.battery.get_range()
练习:
9-6
# 9-6 冰淇淋小店
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.name = restaurant_name
self.type = cuisine_type
def describe_restaurant(self):
print("\nThe restaurant's name is " + self.name.title() + "!")
print("\nThe restaurant is " + self.type + "!")
def open_restsurant(self):
print("\n" + self.name.title() + " is open !")
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name='gg', cuisine_type='dd'):
# flavors = []
super().__init__(restaurant_name, cuisine_type)
self.flavors = ['蓝莓', '草莓', '芒果']
print(self.flavors)
restaurant1 = IceCreamStand()