简体   繁体   中英

How do I resolve this Python inheritance super-child call?

If i'm using a super constructor to create a class that is inherited from a parent class, is it possible to use that same call to set an attribute to create a child class? So in my I am creating an Electric Car. An Electric Car is a child class of a Car. An Electric Car has an attribute battery which will be initialized through its Class constructor. Can I specify the size of the Battery in my initial call to construct Electric Car?

Currently its giving me an error because I have a super call that has less parameters than my Electric car constructor

Ex:

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

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

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

    def describe_battery(self):
        print("Battery size is", self.battery_size)

my_tesla = ElectricCar('TeslaX', 2016)
my_tesla.getInfo()
  print(my_tesla.battery)
my_tesla.battery.describe_battery()

my_big_tesla = ElectricCar('TeslaY', 2016, 90)
my_big_tesla.battery.describe_battery()

You don't give battery size here:

my_tesla = ElectricCar('TeslaX', 2016)

Change it to:

my_tesla = ElectricCar('TeslaX', 2016, 1337)  # 1337 is battery size.

If you wish to supply a default, you should also supply it in ElectricCar like so:

def __init__(self, model, year, battery_size=70):
    super().__init__(model, year)
    self.battery = Battery(battery_size)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM