My code somehow works but I have a few doubts regarding it.
1) I have defined my_car as an object for Car as well as ElectricCar class(Followed instructions). So my_car is exactly which class's instance now?
2) We use inheritance so that we don't have to redefine variables and methods but here I have to reinitialise variables like model,color...etc. Now what's the point of inheriting then?
3) what is more efficient? redefining those variables(model,color,mpg) in the init class of electriccar using self or super is more efficient?
Thanks in advance. I am very new to inheritance so very confused

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,str(self.mpg))
    def drive_car(self):
        self.condition = "used"

class ElectricCar(Car):
    def __init__(self,model, color, mpg, battery_type):
        self.battery_type = battery_type

my_car = Car("DeLorean", "silver",88)
my_car = ElectricCar("test","blue",100,"molten salt")
print my_car.condition
print my_car.condition


its an electric car, first it was a normal Car, then you changed it to an ElectricCar.

We can simplify this:

x = 5
x = 6

x used to be 5, not its 6, you simply re-assigned it

we only have to overwrite init, all the other methods and member variable we inherit.

Its great to inherit from parent, but sometimes certian methods need to be overwritten

if we wouldn't have inherited, you couldn't have used super(), and you would have make all the methods again

i would super(), it fits the programming DRY principal better


Thank You stetim94

Also condition is a class variable right? then why do we use self.condition in the method drive_car since we use the self only with instance variables.?


yes, it is. The course might name it member variable, but the official python docs use class variable.

if we want to access class variable, instance variable or methods in a method, we have to use self.class_variable, self.instance_variable or self.method_name()

the only difference is that methods and class variable are added to self automatically where as for instance variable we have to do this manually (explicit, gives us more control)


Got it! Thanks a lot :smiley:


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