复习--类的继承

继承

class Car():
    
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

class ElectricCar(Car):
  def __init__(self, make, model, year):
    super().__init__(make, model, year) # 在python3中,继承父类方法super括号里不需要实参, 也不需要传递self


在python2.7版本中,继承对象是需要传递两个实参,一个是子类名,另外一个是对象self

class Car():
    
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

class ElectricCar(Car):
  def __init__(self, make, model, year):
    super(ElectricCar, self).__init__(make, model, year)  

给子类添加自己独有属性

class Car():
    
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

class ElectricCar(Car):
  def __init__(self, make, model, year):
         super().
__init__(make, model, year)
    self.battery_size = 70 # g给子类电动车添加一个独有的属性,电瓶容量

在给子类设置独特属性的时候需要注意应该在初始化父类属性后再初始化自己独有属性


如果一个属性或方法是任何父类汽车都有的,而不是子类电动车独有的,那就应该将这个属性或方法加入到Car类而不是ElectricCar类中,这样使用Car类的人就都可以调用,而子类中只处理自己独有的属性和方法。

重写父类的方法

对于父类的方法,子类需要用到,但是直接调用非常不合理,所以就可以在子类中重写父类方法,比如子类电动车并存在油箱剩余油量的方法,所以可以在电动车类中重写父类的剩余油量方法。

class ElectricCar(Car):
    
    def fill_gas_tank(self):
        """ 电动车没有油箱"""
        print("This car doesn't need a gas tank!")

使用继承时,可让子类保留从父类那里继承而来的精华,并剔除不需要的糟粕。

将实例用作属性

在我们类的属性和方法越来越多的情况下,我们可以将类的一部分作为一个独立的类提取出来。可以将大型类拆分成多个协同工作的小类

举例说明

class Battery():
    
    def __init__(self, battery_size=70):
        self.battery_size = battery_size

class ElectricCar(Car):
  def __init__(self, make, model, year):
    super().__init__(make, model, year)
    self.battery = Battery()


原文地址:https://www.cnblogs.com/aaaajayheng1990/p/11024908.html