11/9 Inheritance Question


#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):
        return "This is a %s %s with %s MPG." % (self.color, self.model, str(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):
        Car.__init__(self, model, color, mpg)
        self.battery_type = battery_type
my_car = ElectricCar("molten salt")

Obviously the last line of code above throws an error message for too few arguments. I am just wondering if there is a way to use the concept of inheritance to avoid having to type in all 4 values for my_car all over again after I have already defined the first 3. Just curious


#2

Well, you are creating a new object when you create the new class. As such you have to redefine the parameters again.

One thing you can do is set up defaults so that you only have to enter what you want to override.

Example:

class Car(object):
    condition = "new"
    
    def __init__(self, model='Jaguar', color='Monochrome', mpg='14'):
        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"

Now when you inherit this class you only have to supply what you want. Also when you do this you want to ensure you use named parameters for overriding or you might get confused.

car = Car(color='Black') # Named Arguments