9. Inheritance Which Car is printed?


#1



The both parent and child classes, are named my_car
when I print my_car.display_car()
the child class gets printed
the console print this

This is a Silver Tesla with 80 MPG.
None
None

The question is why was this printed not the parent class and how can i print the parent class?


class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
        
    def display_car(self):
        print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
        
    def drive_car(self):
        self.condition = "used"

my_car = Car("DeLorean", "silver", 88)

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        super(ElectricCar, self).__init__(model, color, mpg)
        self.battery_type = battery_type
    
my_car = ElectricCar("Tesla", "Silver", 80, "molten salt")

print my_car.display_car()


#3

Try to read the post..
My code is fine I am asking some question bro


#4

My apologies. :sweat: I did not fully read your question, I assumed you needed help.


#5

my_car is a variable which could refer to either a car from the parent class or a car from the child class. You first have it set to the parent class but then later in your code you reset my_car to the child class. You cannot print the parent class unless you were to reassign my_car.


#6

Thanks a lot dude

It should have been very obvious, didnt know I'm that dump until now :smiley:


#7

No worries thanks for your concern


#8

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