Inheritance exercise problem


#1

My code fails to update the condition of my_car after I drive it. It prints ‘new’ twice.

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 %s %s with %s MPG." % (self.color, self.model, self.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
  def drive_car(self):
    self.conditon = "like new"
  	
my_car = ElectricCar("VW", "Blue", 100, "molten salt")
print my_car.condition
my_car.drive_car()
print my_car.condition

I can’t see the difference between this and the solution code. I’m sure it’s something stupid. Can anyone tell me what’s happening?


#2

The derivative class should not have this method.

Every new instance inherits the condition from Car and remains new until it is driven.


#3

I’m afraid I don’t understand. I think the derivative class is supposed to have a drive_car() method which overrides the method with the same name in the base class. Acar remains new until I call drive_car() and then becomes either ‘used’ or ‘like’ new depending on whether it’s an instance of the base class or the derivative class. Unfortunately I can’t see the solution code now for some reason.


#4

Okay, that makes sense. Without the exercise in front of us we are left to speculate. Could you please post a link to this exercise? Thanks.


#5

https://www.codecademy.com/courses/learn-python/lessons/classes/exercises/overriding-methods?action=resume_content_item

btw if I make my_car an instance of the base class, I get “new / used” as output, that’s the goal of an earlier exercise.


#6

Try comparing to this spoiler (which gives the correct output, new/like new)…

spoiler
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 {:d} MPG.".format(self.color, self.model, self.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
  def drive_car(self):
    self.condition = 'like new'

my_car = ElectricCar("DeLorean", "silver", 88, 'molten salt')
print my_car.condition
my_car.drive_car()
print my_car.condition

… and just like that…


#7

I finally saw it. (I misspelled ‘conditon’ in the quoted line). Thanks, mtf.


#8

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