为什么要用继承?请看下面两个类
class RobotOne:#第一代机器人
def __init__(self,year,name):
self.year=year
self.name=name
def walking_on_ground(self):
print(self.name+"只能在平地上行走,有障碍物就会摔倒")
def robot_info(self):
print("{0}年产生的机器人{1},是中国研发的".format(self.year,self.name))
class RobotTwo:#第二代机器人
def __init__(self,year,name):
self.year=year
self.name=name
def walking_on_ground(self):
print(self.name+"只能在平地上平稳的行走")
def walking_avoid_block(self):
print(self.name+"可以避开障碍物")
def robot_info(self):
print("{0}年产生的机器人{1},是中国研发的".format(self.year,self.name))
第一个类和第二个类的函数基本都是一样的,显得十分的赘余,所以就产生了继承这种东西,那么如何继承呢,请看下面的代码。
① 类的拓展和重写
class RobotOne:#第一代机器人
def __init__(self,year,name):
self.year=year
self.name=name
def walking_on_ground(self):
print(self.name+"只能在平地上行走,有障碍物就会摔倒")
def robot_info(self):
print("{0}年产生的机器人{1},是中国研发的".format(self.year,self.name))
class RobotTwo(RobotOne):#继承第一代机器人,去掉一模一样的函数
def walking_on_ground(self): #父类里面有的,但是子类里面不一样,这种时候就叫重写
print(self.name+"只能在平地上平稳的行走")
def walking_avoid_block(self): #父类里面没有的,只有子类里面有,这种就叫拓展
print(self.name+"可以避开障碍物")
加入想在子类函数中调用父类的函数怎么调用呢?–直接调用就可以了,父类有的子类都有
def walking_avoid_block(self):
self.robot_info() #直接调用就可以了
print(self.name+"可以避开障碍物")
② 多继承和超继承
class RobotThree(RobotOne,RobotTwo):#第三代机器人,继承了第一代和第二代机器人,多继承中继承的这多个类不能有
相互继承的关系,要是两个独立的没有继承关系的类。且这个两个参数的位置也会影响调用的关系,当这两个类中的函数一样时,哪个在前面就会调用哪个的。
def jump(self):
print(self.name+"可以单膝跳跃")
t=RobotThree("小鱼")#假如RobotOne只有一个参数name,那么调用的时候就只能用一个参数,否则就会报错。但是继承中的RobotTwo又有两个参数,想用RobotTwo中不一样的另一个参数的函数怎么办呢?
这个问题暂时没法解决,所以,在继承多个父类的时候,要求初始化函数一致,或者是干脆没有初始化函数
t.walking_on_ground()
作业:’’‘按照以下要求定义一个游乐园门票类,并创建实例调用函数
完成儿童和大人的总票价统计(人数不定,由输入的人数个数来决定)
1.平日票价100元
2.周末票价为平日票价120%
3.儿童半价’’’
class Tichet:
def __init__(self,price=100):
self.price=price
def total(self):
total=0
day=int(input("您需要购买哪天的票,1-5代表星期一至星期五,6-7代表星期六星期日"))
man=input("请输入您需要购买的大人人数的票")
child=input("请输入您需要购买的儿童人数的票")
if day in range(1,6):
total=int(man)*self.price+int(child)*self.price*0.5
elif day==6 or day==7:
total=int(man)*self.price*1.2+int(child)*self.price*1.2*0.5
else:
print("您的输入有误,请重新输入")
return "您需要支付的总票价为:{0}".format(total)