Python进阶-----在子类中调用父类方法

方法一:指名道姓,即父类名.父类方法()coding

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('开动啦...')

class Subway(Vehicle): #地铁
    def __init__(self,name,speed,load,power,line):
        Vehicle.__init__(self,name,speed,load,power)    #调用父类的构造函数(初始化)
        self.line=line

    def run(self):
        print('地铁%s号线欢迎您' %self.line)
        Vehicle.run(self)                               #调用父类的方法run()

line13=Subway('中国地铁','180m/s','1000人/箱','',13)
line13.run()


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('开动啦...')

方法二: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('开动啦...')

class Subway(Vehicle):  # 地铁
    def __init__(self, name, speed, load, power, line):
        # super(Subway,self) 就相当于实例本身 在python3中super()等同于super(Subway,self)
        super().__init__(name, speed, load, power)     #可以不用写父类名,且省去self参数,默认会传入
        self.line = line

    def run(self):
        print('地铁%s号线欢迎您' % self.line)
        super(Subway, self).run()   #=== super().run()

class Mobike(Subway):  # 摩拜单车
    def a(self):
        super(Mobike, self).run()    #调用地铁类的run方法

line13 = Subway('中国地铁', '180m/s', '1000人/箱', '', 13)
line13.run()
mb = Mobike('摩拜单车','10m/s','1人/车','人工动力',1)
mb.a()

 

posted @ 2018-10-14 23:23  Meanwey  阅读(3769)  评论(0编辑  收藏  举报