Inheritance


#1


https://www.codecademy.com/courses/python-intermediate-en-egNXj/1/3?curriculum_id=4f89dab3d788890003000096#


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):
        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.battery_type=battery_type
        self.model = model
        self.color = color
        self.mpg   = mpg
my_car=ElectricCar("tesla model 3", "red", 300, "molten salt")


#2

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):
	pass
>>> 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.


#3

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