python super()函数错误?

时间:2016-07-29 08:07:18

标签: python python-2.x

class car(object):

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

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

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

TypeError:super()至少需要1个参数(0给定)

super()函数有什么问题?

3 个答案:

答案 0 :(得分:8)

super()(没有参数)是在 python3 中引入的  这是 python2 实现。

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

您可以参考this question了解有关 python2 python3

的一般继承语法问题

答案 1 :(得分:3)

看起来您正在尝试使用Python 3语法,但您使用的是Python 2.在该版本中,您需要将当前类和实例作为参数传递给super函数:

super(electricCar, self).__init__(make, model, year)

答案 2 :(得分:0)

如果您使用的是python 2,则需要使用super方法显式传递您的实例。在python 3或更高版本中,实例变量隐式传递,您不需要指定它。此处self是类car

的实例
super(car, self).__init__(make, model, year)