python-继承

创建一个关于汽车的类,如下:

 1 ''表示汽车的类'''
 2 class car():
 3     def __init__(self,make,model,year):
 4         self.make=make
 5         self.model=model
 6         self.year=year
 7         self.odomember=0
 8     def get_descriptive_name(self):
 9         long_name=str(self.year)+' '+self.make+' '+self.model
10         return long_name.title()
11     def read_odomember(self):
12         print("This car has"+str(self.odomember)+"miles on it.")
13     def update_odomember(self,mileage):
14         if mileage>=self.odomember:
15             self.odomember=mileage
16         else:
17             print("Yor Can't roll back an odomember!")
18     def increment_odomeber(self,miles):
19         self.odomember+=miles
20 my_user_car=car('China','奥迪',2016)
21 print(my_user_car.get_descriptive_name())
22 my_user_car.read_odomember()
23 my_user_car.odomember=12
24 my_user_car.read_odomember()
25 my_user_car.update_odomember(260)
26 my_user_car.read_odomember()
27 my_user_car.increment_odomeber(16000)
28 my_user_car.read_odomember()
29 """继承"""
30 class battery():
31     def __init__(self,battery_size=70):
32         self.battery_size=battery_size
33     def describe_battery(self):
34         print("The ElectricCar has a "+str(self.battery_size) + "-KWH battery")
35     def get_range(self):
36         if self.battery_size==70:
37             range=240
38         elif self.battery_size==80:
39             range=320
40         messgae="This car can go approximately"+str(range)
41         messgae+="mules on a full charge"
42         print(messgae)
43 
44 class ElectricCar(car):
45     def __init__(self,make,model,year):
46         super().__init__(make,model,year)
47         self.battery=battery()
48 
49 my_tesla=ElectricCar('tesla','model s',2016)
50 print(my_tesla.get_descriptive_name())
51 my_tesla.battery.describe_battery()
52 my_tesla.battery.get_range()

与c#中的继承大同小异

posted @ 2018-07-24 17:52  InXin  阅读(152)  评论(0编辑  收藏  举报