class Car():
def __init__(self,year,make,model):
self.year=year
self.make=make
self.model=model
self.distant=10
def describe_car(self):
long_name=str(self.year)+' '+self.make+' '+self.model
return long_name
def read_mile(self,miles):
if miles>self.distant:
self.distant=miles
else:
print('\nyou can not roll back the distant')
def increase_distant(self,mileage):
if mileage>0:
self.distant+=mileage
else:
print('\nthe increase must bigger than 0')
def distants(self):
print('\nThe car has '+str(self.distant)+' miles on it')
class Auto_car(Car):
#创建Car的一个子类Auto_car,子类完整的继承了父类的各种属性和函数,并且可以重新定义父类中的方法
def __init__(self,year,make,model):
super().__init__(year,make,model) #super 连接父类和子类
首先是Car类的代码。创建子类时,父类必须包含在当前文件中,且位于子类前面。定义子类时,必须在括号内指定父类的名称。方法_init_()接受创建Car实例所需的信息
super()是一个特殊的函数,帮助python将父类和子类关联起来。这行代码让python调用子类的父类的方法_init_(),让子类实例包含弗雷德所有属性。父类也称为超类(superclass),名称super因此而得名。
重写父类的方法:
对于父类的方法,只要他不符合子类模拟的实物的行为,都可对其重写。为此,可在子类中定义一个这样的方法,即他与要重写的父类方法同名。这样,python将不会考虑这个父类方法,而只关注你在子类中定义的相应方法。
假设Car类有一个名为fill_gas_tank()的方法,它对电动汽车来说毫无意义,因此你可能想重写它。下面演示了一种重写方式:
class ElectricCar(Car):
...ship
def fill_gas_tank(self):
'''电动汽车没有油箱'''
print('This car doesn't need a gas tank!')
现在。如果有人对电动汽车调用方法fill_gas_tank(),python将忽略Car类中的方法fill_gas_tank(),转而运行上述代码。使用继承时,可让子类保留从父类那里继承而来的精华,并剔除不需要的糟粕。