9.3继承
1.子类的继承方法 __init __()
Car:父类
ElectricCar:子类
定义子类时,在括号内指定父类名称: class ElectricCar(Car)
初始化父类属性值: super().__init __()
super()函数让ElectricCar 实例包含父类的所 有属性
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')
def update_odometer(self,mileage):
if mileage>=self.odometr_reading:
self.odometer_reading=mileage
else:
print('You cant roll back an odometer')
def increment_odometer(self,miles):
self.odometer_reading+=miles
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())
运行结果:
2.给子类定义属性和方法
class Car:
--snip--
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.describe_battery()
运行结果:
This car has a 70-kwh battery
3.重写父类的方法
Car 类有一个名为fill_gas_tank() 的方法,电动车没有油箱,因此我们在ElectricCar类中重写它。
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
self.gas=5
--snip--
def fill_gas_tank(self):
print('The gas tank has '+str(self.gas)+'-l gas in it')
class ElectricCar(Car):
--snip--
def fill_gas_tank(self):
print('Do not need a gas tank')
my_car=Car('audi','model s',2020)
my_tesla=ElectricCar('tesla','model s',2016)
my_car.fill_gas_tank()
my_tesla.fill_gas_tank()
运行结果:
4.将实例用作属性
有时,我们可能需要将类的一部分作为一个独立的类提取出来,将大型类拆分成多个协同工作的小类。
例如,不断给ElectricCar 类添加细节时,我们可能会发现其中包含很多专门针对汽车电瓶的属性和方法。在这种情况下,我们可将这些属性和方法提取出来,放到另一个名为Battery 的类中,并将一个Battery 实例用作ElectricCar 类的一个属性:
class 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):
#初始化父类的属性
super().__init__(make,model,year)
self.battery=Battery()
def fill_gas_tank(self):
print('Do not need a gas tank')
my_tesla=ElectricCar('tesla','model s',2016)
my_tesla.battery.describe_battery()
运行结果:
This car has a 70-kwh battery.
在Battery类中 设置更详细的get_range()函数:
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
self.gas=5
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')
def update_odometer(self,mileage):
if mileage>=self.odometr_reading:
self.odometer_reading=mileage
else:
print('You cant roll back an odometer')
def increment_odometer(self,miles):
self.odometer_reading+=miles
def fill_gas_tank(self):
print('The gas tank has '+str(self.gas)+'-l gas in 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 can can go approximately '+str(range)+' km .'
print(message)
class ElectricCar(Car):
def __init__(self,make,model,year):
#初始化父类的属性
super().__init__(make,model,year)
self.battery=Battery()
def describe_battery(self):
print('This car has a '+str(self.battery_size)+'-kwh battery')
def fill_gas_tank(self):
print('Do not need a gas tank')
my_tesla=ElectricCar('tesla','model s',2016)
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
练习
1.冰淇淋小店 :冰淇淋小店是一种特殊的餐馆。编写一个名为IceCreamStand 的类,让它继承你为完成练习9-1或练习9-4而编写的Restaurant 类。这两个版 本的Restaurant 类都可以,挑选你更喜欢的那个即可。添加一个名为flavors 的属性,用于存储一个由各种口味的冰淇淋组成的列表。编写一个显示这些冰淇淋 的方法。创建一个IceCreamStand 实例,并调用这个方法。
class Restaurant():
def __init__(self,name,cuisine_type):
self.name=name
self.cuisine_type=cuisine_type
number_served=0
def describe_restaurant(self):
print("The restaurant's name is "+self.name.title()+'.')
print("The cuisine_type of this restaurant is "+self.cuisine_type)
def open_restaurant(self):
print(self.name.title()+' is open')
def set_number_served(self,number):
self.number_served=number
print('就餐人数:'+str(self.number_served))
def increment_number_served(self,increment):
self.number_served+=increment
print('新增后的就餐人数:'+str(self.number_served))
class IceCreamStand(Restaurant):
def __init__(self,name,cuisine_type):
super().__init__(name,cuisine_type)
self.flavors=['cherry','orange','milk']
def show_flavor(self):
print('you can choose ')
for flavor in self.flavors:
print(flavor+'icecream')
my_icecream=IceCreamStand('pudding','dessert')
my_icecream.show_flavor()
2 . 管理员 :管理员是一种特殊的用户。编写一个名为Admin 的类,让它继承你为完成练习9-3或练习9-5而编写的User 类。添加一个名为privileges 的属性,用 于存储一个由字符串(如"can add post" 、“can delete post” 、“can ban user” 等)组成的列表。编写一个名为show_privileges() 的方法,它 显示管理员的权限。创建一个Admin 实例,并调用这个方法。
class User():
def __init__(self,first_name,last_name,location):
self.first_name=first_name
self.last_name=last_name
self.location=location
self.login_attempts=0
def describe_user(self):
name=self.first_name+self.last_name
print('hello,'+name)
print('Hope u hava a goog time in '+self.location)
def increment_login_attempts(self):
self.login_attempts+=1
print('用户尝试登陆次数:'+str(self.login_attempts))
def reset_login_attempts(self):
self.login_attempts=0
print('重置用户尝试登陆次数:'+str(self.login_attempts))
class Admin(User):
def __init__(self,first_name,last_name,location):
super().__init__(first_name,last_name,location)
self.privileges=['can add post','can delete post','can ban user']
def show_privileges(self):
for privilege in self.privileges:
print(self.first_name+self.last_name+privilege)
my_admin=Admin('ming','jing','work')
my_admin.describe_user()
my_admin.show_privileges()
运行结果:
3.权限 :编写一个名为Privileges 的类,它只有一个属性——privileges ,其中存储了练习9-7 所说的字符串列表。将方法show_privileges() 移到这 个类中。在Admin 类中,将一个Privileges 实例用作其属性。创建一个Admin 实例,并使用方法show_privileges() 来显示其权限.
class User():
def __init__(self,first_name,last_name,location):
self.first_name=first_name
self.last_name=last_name
self.location=location
self.login_attempts=0
def describe_user(self):
name=self.first_name+self.last_name
print('hello,'+name)
print('Hope u hava a goog time in '+self.location)
def increment_login_attempts(self):
self.login_attempts+=1
print('用户尝试登陆次数:'+str(self.login_attempts))
def reset_login_attempts(self):
self.login_attempts=0
print('重置用户尝试登陆次数:'+str(self.login_attempts))
class Privileges():
def __init__(self):
self.privileges=['can add post','can delete post','can ban user']
def show_privileges(self):
for privilege in self.privileges:
print('Admins '+privilege)
class Admin(User):
def __init__(self,first_name,last_name,location):
super().__init__(first_name,last_name,location)
self.privileges=Privileges()
my_admin=Admin('ming','jing','work')
my_admin.describe_user()
my_admin.privileges.show_privileges()
4 .电瓶升级 :在本节最后一个electric_car.py版本中,给Battery 类添加一个名为upgrade_battery() 的方法。这个方法检查电瓶容量,如果它不是85,就将它 设置为85。创建一辆电瓶容量为默认值的电动汽车,调用方法get_range() ,然后对电瓶进行升级,并再次调用get_range() 。你会看到这辆汽车的续航里程增 加了。
class Car():
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
self.gas=5
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')
def update_odometer(self,mileage):
if mileage>=self.odometr_reading:
self.odometer_reading=mileage
else:
print('You cant roll back an odometer')
def increment_odometer(self,miles):
self.odometer_reading+=miles
def fill_gas_tank(self):
print('The gas tank has '+str(self.gas)+'-l gas in 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 can can go approximately '+str(range)+' km .'
print(message)
def upgrade_battery(self):
if self.battery_size!=85:
self.battery_size=85
class ElectricCar(Car):
def __init__(self,make,model,year):
#初始化父类的属性
super().__init__(make,model,year)
self.battery=Battery()
def describe_battery(self):
print('This car has a '+str(self.battery_size)+'-kwh battery')
def fill_gas_tank(self):
print('Do not need a gas tank')
my_tesla=ElectricCar('tesla','model s',2016)
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()
运行结果: