尝试使用super().__ init__时出错

时间:2016-10-13 23:42:30

标签: python inheritance init super

我是Python的新手,并且从我正在使用的一本书中获取了下面的代码摘录。

它列在完全下面,因为它在书中已经编写和解释但是却引发了以下错误:

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

当我尝试给super一个参数时,它告诉我它必须是类型。

我搜索了多个主题并且还没有运气。

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())

2 个答案:

答案 0 :(得分:2)

你正在运行Python 2,而不是Python 3. Python 2's super需要至少一个参数(定义此方法的类型),通常是两个(当前类型和self) 。只能在没有参数的情况下调用Python 3's super

通过在脚本顶部添加以下内容进行确认,该脚本将报告您在以下位置运行的实际版本:

import sys

print(sys.version_info)

注意:由于您在ElectricCar __init__之外没有做任何事情,除了委托给Car' __init__相同的参数,您可以完全跳过为__init__定义ElectricCar。如果初始化__init__涉及执行与初始化ElectricCar不同的操作,则只需要使用显式委派覆盖Car,否则在初始化{{{}时会自动调用Car初始化程序1}}未定义Car的子类。如上所述,您可以将__init__简化为:

ElectricCar

并且行为相同(通过避免不必要的拦截和class ElectricCar(Car): pass 的授权,它会运行得更快一些)。

答案 1 :(得分:0)

在python 2.7中,你的ElectricCar类看起来像这样:

class Car(object):
    blah blah blah


class ElectricCar(Car):
    def __init__(self, make, model, year):
        super(ElectricCar, self).__init__(make, model, year)
相关问题