9 - Inheritance


#1



The exercise

So, this is my code:

class Car(object):
    condition = "new";
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
        
    def display_car(self):
        return "This is a " + self.color + " " + self.model + " with " + str(self.mpg) + " MPG.";
        
    def drive_car(self):
        self.condition = "used";
        
class ElectricCar(Car):
    def __init__(self, battery_type):
        self.battery_type = battery_type;

my_car = ElectricCar("Ibiza", "red", 88, "molten salt")

Error message i get is:

"Traceback (most recent call last):
File "python", line 18, in
TypeError: init() takes exactly 2 arguments (5 given)"

i've checked the forum and found a solution that looks like this:

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        super(ElectricCar, self).__init__(model, color, mpg);
        self.battery_type = battery_type;

so what i don't get is why use a child class if i need to write all the variables again?
isn't it simpler to just add another variable to the parent class?

Also, is there another way (or more than one), in addition to what worked for me, to achieve this result?

thanks.


#2

in java you need to put parent variables into chiled class constructor, same as here, and you don't need to self(this) them, just use super(put parent variables here), guess that goes for all oop languages


#3

@cssninja36613

Hi, I don't know much about Python and was hoping for an answer to exactly this. I searched around and found an article that explained abstracting really well and deals with exactly this type of problem. It would be nice if the lesson addressed the repetition.

https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/