noob2014
noob2014

Reputation: 89

Python class inheritance not doing what I think it should

I think I understand class inheritance in python, basically you can inherit the attributes of the parent class on the child class for re-usability and also to "add" to it to make even more complex classes.

Here is my question: I have a Car class below that has (model, color, mpg) as parameters, after that I created a new child class called ElectricCar that inherits from the parent Car class...and now when I call ElectricCar with "(battery_type, model, color, mpg), I get the following error:

TypeError: init() takes exactly 2 arguments (5 given)

I know got to fix it. I need to add self.model, self.color and self.mpg to the ElectricCar class. But why do i have to do that? It seems this defeats the purpose of inheritance if I need to re-define again on the child class.

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

my_car = Car("DeLorean", "silver", 88)

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

my_car = ElectricCar("molten salt", "Honda","black", "33")

Upvotes: 2

Views: 87

Answers (3)

vaultah
vaultah

Reputation: 46593

I need to add self.model, self.color and self.mpg to the ElectricCar class.

You don't. Python allows you to call methods of parent classes you've replaced. You just have to call the constructor of the parent class explicitly.

The first argument of ElectricCar.__init__ is the battery type. Store the rest of positional arguments in a list (args) and unpack them to the parent constructor:

class ElectricCar(Car):
    def __init__(self, battery_type, *args):
        super(ElectricCar, self).__init__(*args) # super().__init__(*args) in Py3k+
        self.battery_type = battery_type

Upvotes: 5

Robert Jacobs
Robert Jacobs

Reputation: 3360

You need to pass model, color, mpg in your ElectricCar class. Then you can call super to initialize the base class.

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg
        print model
        print color
        print  mpg

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

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

my_car = ElectricCar("molten salt", "Honda","black", "33")

Upvotes: 0

zondo
zondo

Reputation: 20366

When you define the __init__ method, you are overriding the__init__ method of the parent class. Such overriding is why the super() function was created.

Upvotes: 2

Related Questions