9. Inheritance (Confusion about Parent/Child Relationship)


Hi folks! I'm wondering why, when you inherit a parent class, you still have to include all the previous member variables. Here is the code I wrote, which passes:

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, model, color, mpg, battery_type):
        self.model = model
        self.color = color
        self.mpg = mpg
        self.battery_type = battery_type

my_car = Car("DeLorean", "silver", 88)
my_car = ElectricCar("Mazda 2", "blue", 34, "molten salt")

I thought I could basically append battery_type to the Car class variable. It threw an error, so I typed out all the previous variables. My question: if you still have to duplicate all the variables in the Parent class, why not just write a new class that is independent of the Parent?



Did you read anything about importing the parent class ?


Um, yes. This is not a helpful response. I clearly asked a question that shows I've read it, but am confused by one aspect of it. Additionally, I came across another site that seemed to suggest inheritance was not the preferred way at all.


The reason I asked you about whether you read up on importing is because import is how you carry out inheritance from the parent class.
I think the other method you're referring to is composition but for simple cases like this you should understand the purpose of the import before you progress.


Hmm. Is "import" different from passing the parent class to the child argument? I think we might be talking about two different things...

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
             comment this out
             self.model = model
             self.color = color
             self.mpg = mpg
        self.battery_type = battery_type


@sardawson perhaps this little article on tutorialspoint could help clear things up


I was just doing this exercise and wondering the same thing. Seems strange that they wouldn't mention how to import the parent class since that's what this exercise is trying to teach. Thanks dondabrera for showing how it's done!


Thanks, rydan! I'll take a look.


Yeah, the inheritance part really threw me off as well. Thanks for the clarification.


Your reference to importing from a parent class using the notation Parent.init( ) has not been covered at all on this course. I am successfully more confused now.


This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.