· 子类继承父类所有的属性和方法,同时定义自己的
· 父类必须包含在当前文件中???????不包含的方法???
· 父类在子类之前
9.3.1子类的方法__init__:
class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) |
Super()让子类包含父类所有的属性
如果super()函数输入了self:
class electrical_car(Car): def __init__(self,make,model,year): super().__init__(self,make,model,year) |
Error:__init__()takes 4 positional arguments but 5 were given
认为:seper()中的额外的self被当做一个新的形参
9.3.2子类定义属性和方法
属性:直接添加就好
class electrical_car(Car): def __init__(self,make,model,year): super().__init__(self,make,model,year) self.battery_size = 70 |
另一种方法
class electrical_car(Car): def __init__(self,make,model,year,battery_size): super().__init__(make,model,year) self.battery_size = battery_size
def describe_battery(self): return self.battery_size
mycar = electrical_car('tesla','model s','2016','70') print(mycar.describe_battery()) |
9.3.3重写父类方法
子类方法名和父类相同即可
9.3.4 将实例用作属性——大类拆分成小类
a. 一个爹+一个隔壁老王
class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name (self): long_name = str(self.year) + ' ' + self.make + ' ' +self.model return long_name.title()
class battery(): def __init__(self,battery_size): self.battery_size = battery_size def describe_battery(self): return 'this car has a '+ str(self.battery_size)+'kwh battery'
class electrical_car(Car): def __init__(self,make,model,year): super().__init__(make,model,year) self.battery = battery()
mycar = electrical_car('tesla','model s','2016') print(mycar.battery.describe_battery()) |
mycar.battery.describe_battery()→调用实例mycar中属性self.battery中的describe_battery()方法
self.battery = battery()→Python创建一个新的battery实例并将该实例储存在属性self.battery中
因此每一个electrical_car实例都包含一个自动创建的battery实例
局限性:battery()只能作为实例!无法在创造实例时输入battery_size的值
伪修改:直接修改实例mycar中的属性→9.2 方法2
mycar = electrical_car('tesla','model s','2016') mycar.battery.battery_size = 233 print(mycar.battery.describe_battery()) |
b. 两个爹——多重继承
#待续