2019年7月28日 在子类中调用父类的方法 happy birthday
class Vehicle: country='China' def __init__(self,name,speed,load,power): self.name=name self.speed=speed self.load=load self.power=power def run(self): print('%s is running'%self.name) class Subway(Vehicle): def __init__(self,name,speed,load,power,line): # self.name=name # self.speed=speed # self.load=load # self.power=power Vehicle.__init__(self,name,speed,load,power)#子类中调用父类的方法,就是上面那段代码,这里self是需要的,因为是在对象在调用类的方法 self.line=line def show_info(self): print(self.name,self.speed,self.load,self.power,self.line) def run(self): Vehicle.run(self)#注意传递self line13=Subway('bjdt','100km/s',5000,'E','13#') line13.show_info() line13.run()
》》》
bjdt 100km/s 5000 E 13#
bjdt is running
super()方法
class Vehicle: country='China' def __init__(self,name,speed,load,power): self.name=name self.speed=speed self.load=load self.power=power def run(self): print('%s is running'%self.name) class Subway(Vehicle): def __init__(self,name,speed,load,power,line): # self.name=name # self.speed=speed # self.load=load # self.power=power # Vehicle.__init__(self,name,speed,load,power)#子类中调用父类的方法,就是上面那段代码,这里self是需要的,因为是在对象在调用类的方法 super().__init__(name,speed,load,power) #super方法不用传递self,通过super方法可以直接调用父类方法 self.line=line def show_info(self): print(self.name,self.speed,self.load,self.power,self.line) def run(self): # Vehicle.run(self)#注意传递self super().run() #super方法不用传递self,通过super方法可以直接调用父类方法 line13=Subway('bjdt','100km/s',5000,'E','13#') line13.show_info() line13.run()
>>>
bjdt 100km/s 5000 E 13#
bjdt is running