• 子类中调用父类的方法


    父类名 . __init__(self, ...)

    可以将父类中的init中的属性重复调用,减少代码的重复

    class Vehicle:
        def __init__(self, name, speed, load, power):
            self.name = name
            self.speed = speed
            self.load = load
            self.power = power
    
        def run(self):
            print('%s我开动啦'%self.name)
    
    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.line)
    
    
    
    line1 = Subway('郑州地铁', '30m/s','500','电', '1号')
    line1.show_info() #调用自身的方法
    line1.run()  #调用父类中的类方法
    

      

    父类名 . 函数名(self)

    子类中调用父类中类方法的逻辑

    class Vehicle:
        def __init__(self, name, speed, load, power):
            self.name = name
            self.speed = speed
            self.load = load
            self.power = power
    
        def run(self):
            print('%s我开动啦'%self.name)
    
    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.line)
    
        def run(self):
            Vehicle.run(self)  #加上这句,可以实现同名函数,调用父类中的逻辑
            print('%s我来自子类'%self.line)
    
    line1 = Subway('郑州地铁', '30m/s','500','电', '1号线')
    line1.show_info() #调用自身的方法
    line1.run()
    

    super 方法

    调用父类逻辑时,不用担心类名的变动

    class Vehicle:
        def __init__(self, name, speed, load, power):
            self.name = name
            self.speed = speed
            self.load = load
            self.power = power
    
        def run(self):
            print('%s我开动啦'%self.name)
    
    class Subway(Vehicle):
        def __init__(self,name, speed, load, power,line):
            # Vehicle.__init__(self, name, speed, load, power)
            super().__init__(name, speed, load, power)    #super 方法,这样就不用担心类名被修改
            self.line = line
    
        def show_info(self):
            print(self.name, self.line)
    
        def run(self):
            # Vehicle.run(self)  #加上这句,可以实现同名函数,调用父类中的逻辑
            super().run()  #效果和上面代码一样,更适合
            print('%s我来自子类'%self.line)
    
    line1 = Subway('郑州地铁', '30m/s','500','电', '1号线')
    line1.show_info() #调用自身的方法
    line1.run()  #调用父类中的类方法
    

    super().__init__(name, speed, load, power) 等同于:

        super(Subway, self).__init__(name, speed, load, power) 
    

      

    一个奋斗中的产品小白
  • 相关阅读:
    MySQL binlog_ignore_db 参数最全解析
    推荐几款MySQL相关工具
    MySQL从库维护经验分享
    swaggert随笔
    springBoot
    git-本地仓库操作
    springboot初识
    spring data jpa
    mybatis复习笔记----关于一些需记忆的点
    mybatis复习笔记----关于标签
  • 原文地址:https://www.cnblogs.com/dabai123/p/11462638.html
Copyright © 2020-2023  润新知