Hatcamel
Hatcamel

Reputation: 9

Error trying to use super().__init__

I am fairly new to Python and have taken the code excerpt below from a book I'm working with.

It is listed below exactly as it is written and explained in the book but yet it throws the following error:

TypeError: super() takes at least 1 argument (0 given)

When I try to give super an argument, it tells me it needs to be of type.

I've searched multiple threads and haven't had any luck yet.

class Car():
    """A simple attempt to represent a car"""

    def __init__(self, make, model, year):
        """Initialize attributes to describe a car"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0


    def get_descriptive_name(self):
        """Return a neatly formatted descriptive name."""
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

class ElectricCar(Car):

    def __init__(self, make, model, year):
        super().__init__(make, model, year)


my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())

Upvotes: 1

Views: 1658

Answers (2)

blackappy
blackappy

Reputation: 665

In python 2.7 your ElectricCar class would look like this:

class Car(object):
    blah blah blah


class ElectricCar(Car):
    def __init__(self, make, model, year):
        super(ElectricCar, self).__init__(make, model, year)

Upvotes: -1

ShadowRanger
ShadowRanger

Reputation: 155333

You're running Python 2, not Python 3. Python 2's super requires at least one argument (the type in which this method was defined), and usually two (current type and self). Only Python 3's super can be called without arguments.

Confirm by adding the following to the top of your script, which will report the actual version you're running under:

import sys

print(sys.version_info)

Note: Since you're not doing anything in ElectricCar's __init__ aside from delegating to Car's __init__ with the same arguments, you can skip defining __init__ for ElectricCar entirely. You only need to override __init__ with explicit delegation if initializing ElectricCar involves doing something different from initializing a Car, otherwise, Cars initializer is called automatically when initializing a Car subclass that does not define __init__. As written, you could simplify ElectricCar to:

class ElectricCar(Car):
    pass

and it would behave identically (it would run slightly faster by avoiding the unnecessary interception and delegation of __init__, that's all).

Upvotes: 2

Related Questions