why I have to define self.model, self.color and self.mpg variable in class ElectricCar if it is a child class of Car?

 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 str("This is a %s %s with %s MPG.") %(self.color, self.model, self.mpg)
    def drive_car(self):

my_car = Car("DeLorean", "silver", 88)
print my_car.condition
print my_car.condition

class ElectricCar(Car):
    def __init__(self,model,color,mpg,battery_type):
        self.model = model
        self.color = color
        self.mpg   = mpg
my_car=ElectricCar("tesla model 3", "red", 300, "molten salt")


ElectricCar does inherit the Car class __init__. However, you override it the moment you define __init__ in the ElectricCar class. Look:

>>> class A(object):
	def __init__(self):
		self.a = "Class A"	
>>> class B(A):
>>> class C(A):
	def __init__(self):
		self.a = "Class C not A"
>>> A().a
'Class A'
>>> B().a
'Class A'
>>> C().a
'Class C not A'

So because you override the __init__ you have to explicitly inherit it to get what it contained in it added to the child class's one. Redefining the __init__ will not override anything else that isn't contained within it; however, you could override anything that the child would inherit by redfining it in the child.


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