Overiding methods


#1



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 %i MPG." %(self.color,self.model,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,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("Tesla","Electrci Blue",20,"molten salt")        
        
print my_car.condition

my_car.drive_car()

print my_car.condition


        
        

       ***************************************************************************
VERSUS
***********************************************************************************

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 %i MPG." %(self.color,self.model,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,model, color,mpg,battery_type):
        self.model = model
        self.color = color
        self.mpg   = mpg
        self.battery_type = battery_type
        
my_car = ElectricCar("Tesla","Electrci Blue",20,"molten salt")               


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

my_car.drive_car()

print my_car.condition

THE first one works while the second one doesn't . all i did was just changed the arrangement of the code.
initially python never gave errors .. butt since classes it does why is that so.


#2

Hello @drnikhil,

1.Define a class
2.Then create instances.

We see here that we did not even defined our class ElectricCar and tried to create my_car instance,

This will probably give us "unexpected indentation error"

my_car = ElectricCar("Tesla","Electrci Blue",20,"molten salt")

Try moving this line after you define drive_car() inside the ElectricCar,


#3

thank you..it works.. but does the arrangement or the order of statements matter?


#4

Yes, It does.
also the indentation matters that's broken by early introduction of that line.


#5

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