Overidding Methods


#1

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

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):
    my_car.condition = "used"
    
my_car = Car("DeLorean", "silver", 88) ##HERE Note how we have to shift the my_car object definition line to after the methods instead of before the drive_car() method.
print my_car.condition
print my_car.drive_car()
print my_car.condition

class ElectricCar(Car):
  def __init__(self, battery_type, model, color, mpg):
    self.battery_type = battery_type
    self.model = model
    self.color = color
    self.mpg   = mpg
    def drive_car(self):
      my_car.condition = "like new"
my_car = ElectricCar("molten salt", "Aston Martin", "black", 95) #HERE 
print my_car.condition
print my_car.drive_car()
print my_car.condition

Not Stuck, All great just need clarification. I have noticed that the code won’t run after creating methods with their own member variables unless we shift or move the new instances/objects.
i.e my_car = Car(“DeLorean”, “silver”, 88) and my_car = ElectricCar(“molten salt”, “Aston Martin”, “black”, 95)
Is this some bug or is this correctly so, that we have to move these instances in place after creating the class methods so that they can be executed. Does python have a way of executing such code in some chronological order?

<What do you expect to happen instead?>
For instance the following code format won’t run and gives an indentation error. Not untill I move the line my_car object that it runs.

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):
    my_car.condition = "used"
    
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
print my_car.drive_car()
print my_car.condition

class ElectricCar(Car):
  def __init__(self, battery_type, model, color, mpg):
    self.battery_type = battery_type
    self.model = model
    self.color = color
    self.mpg   = mpg
my_car = ElectricCar("molten salt", "Aston Martin", "black", 95)   #HERE, This gives an indentation error located at next line.
    def drive_car(self):
      my_car.condition = "like new"

print my_car.condition
print my_car.drive_car()
print my_car.condition


#2

The instantiation should take place outside of the class.


#3

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