python之子类调用父类的两种方式

第一种方式:直接在子类中调用父类名

调用方式如下:

Vehicle.__init__(self, name, speed, load,power) # 调用父类的实例
Vehicle.run(self) #调用父类的方法

下面给出具体样例:

#直接调用父类名
class Vehicle:  # 父类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): # 子类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:  # 父类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): # 子类Subway继承父类Vehicle
    def __init__(self,name,speed,load,power,line):
        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):
        super().run()
        print("%s %s 线开动啦" % (self.name, self.line))

d1 = Subway("北京地铁","10km/h",10000,"电",13)
d1.show_info()
d1.run()

两种调用方法对比:

调用实例:

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

调用方法:

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

用super方法调用父类方法更好,主要在于:

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

你可能感兴趣的:(python,开发语言,numpy)