Overriding methods


#1

need some help with this

driving the electric car.

in the following lines of code I get the following error:

  File "python", line 28
    def drive_car(self):
   ^
IndentationError: unexpected indent

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)

print my_car.condition
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", "Coralla", "White", 35)

    def drive_car(self):
        self.condition = "like new" 

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

So I remove that indent and run the program. But when I drive the car, it is not printing "like new" but rather:

new
used
new
used

so can some assist me in understanding why the Overriding methods is not working when I drive the electric car.

Thanks


#2

drive_car should be a method of ElectricCar class, then after the class create a class instance (my_car)


#3

is drive_not a method of the electric car class when I define it by indentation within the Electric_Car class?

Also, I have and instance of my car as well. Should I indent that?


#4

but your class instance should be after you finished your class, but your drive_car method is after the instance, that is not possible

the class should first be build (all its methods), and then you need to create class instance


#5

ok, I see, sorry didn't know that. thanks, it worked


#6

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