第一种方式

直接在子类中调用父类名:

  • Vehicle.__init__(self,name,speed,load,power)#调用父类的实例
  • Vehicle.run(self) #调用父类的方法
#直接调用父类名
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 show_info(self):
        print(self.name,self.speed,self.load,self.power,self.line)
        
    def run(self):
        Vehicle.run(self)  #调用父类的方法
        print("%s %s 线开动啦" % (self.name, self.line))
d1 = Subway("北京地铁","10km/h",10000,"",13)
d1.show_info()
d1.run()

第二种方式

调用super方法:

  • super().__init__(name,speed,load,power)
  • super().run()
#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):
        #Vehicle.__init__(self,name,speed,load,power)#调用父类的实例
        super().__init__(name,speed,load,power)
        self.line = line

    def show_info(self):
        print(self.name,self.speed,self.load,self.power,self.line)

    def run(self):
        #Vehicle.run(self)  #调用父类的方法
        super().run()
        print("%s %s 线开动啦" % (self.name, self.line))
d1 = Subway("北京地铁","10km/h",10000,"",13)
d1.show_info()
d1.run()

两种调用方法对比

调用实例:

  1. Vehicle.__init__(self,name,speed,load,power)#调用父类的实例
  2. super().__init__(name,speed,load,power)

调用方法:

  1. Vehicle.run(self)  #调用父类的方法
  2. super().run()

用super方法调用父类方法的好处:

1、不用再写父类名,就算父类名字改变,子类调用父类的逻辑也不需要改动;2、不用再传self参数,默认把self传进去了

版权声明:本文为songzhixue原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/songzhixue/p/10064124.html