Overriding methods


#1



https://www.codecademy.com/en/courses/python-intermediate-en-egNXj/1/4?curriculum_id=4f89dab3d788890003000096
My Code goes Here..

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"
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,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("BMW i8", "blue", 88,"molten salt")
print my_car.condition
print my_car.drive_car()



In the 2nd last line, I expected to print out "like new" but it printed out "new"

If we Interchange the position of the last two code i.e

print my_car.condition
print my_car.drive_car()

to

print my_car.drive_car()
print my_car.condition

then it is working fine..

My question is that why is this happening? Why the order of printing is changing the whole answer?


#2

my_car condition is changing after using .drive_car() method, that's why order of printing is changing answer.

On __init__ car condition is set to "new". If you check condition after creating a new instance, it will return "new". In drive_car() you are changing it's condition to "like new". So after using .drive_car() it's condition is set to "like new".

my_car=ElectricCar("BMW i8", "blue", 88,"molten salt")
print my_car.condition # new
my_car.drive_car()
print my_car.condition # like new

Also, you don't need to print my_car.drive_car(), because it's not returning anything. It will always return None, because Python functions always return something, but if no return is declared, the function will return None.