Overriding Methods


#1

I’m confuzzled.
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):
    print "This is a %s %s with %s MPG." % (self.color, self.model, str(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

This code prints out

new
like new

my_car variable refers to the ElectricCar class, but it still prints out new, which is the assignment to the variable condition in the parent Car class.
If my_car is already referring to the ElectricCar class, why does it still prints the word new ?

I hope I’m being clear. It’s hard to try and explain code questions :smiley:


#2

the point of inheritance is to inherit member variables (like new) and methods from parents. So child class inherits everything, and you can overwrite what you need. This can be very handy


#3

Thanks for the reply.

I can see why it’s handy. But what I don’t get is why it prints out new first and then like new
I know my_car.drive_car() has something to do with it, but how ? Since the .drive_car() method is also in the parent Car class


#4

yes, but my_car is an instance of ElectricCar, so python will first check if drive_car method exist in ElectricCar class, before going to parent class.


#5

Okay so why doesn’t it do that right away? At the first print my_car.condition


#6

Does it always look first at the parent class unless asked otherwise?


#7

too many it and that in the question without a clear indication what is referenced.

Child class inherits from parent, then the child class overwrites the methods and member variables from parent (if you decide to overwrite a method/member variable in child class)

Given condition isn’t overwritten, it keeps the value given to it by parent class.

Its the way its implemented in python.