Inheritance


#1



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


In child class 'ElectricCar' if I have to define all the arguments 'model, color, mpg' again then what's the point of inheriting from parent class 'Car'?


Why can't we define only battery_type and inherit others from Car class?

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


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 %d MPG." %(self.color, self.model, self.mpg)
    def drive_car(self):
        self.condition = "used"
        
        
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("McLoren", "golden", 60, "molten salt")


#2

Hi @objectace67907

To answer your question, the reason we put all of this:

inside the child's class is simply to override the default initializer in the super class to add the battery_type to your initializer. Then you have to rewrite all the init part otherwise writing this:

def init(self, battery_type):
  self.battery_type = battery_type

will simply mean that you will remove all the other properties from the inherited class and replace them with simply the battery_type one. And of course, that's not what you want.

Hope you understood my explanation! :wink:


#3

We can.

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        Car.__init__(self, model, color, mpg)
        self.battery_type = battery_type
        
my_car = ElectricCar("Prius", "red", 99, "molten salt")
print (my_car.model)    # Prius

Or,

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

#4

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