TypeError:super()至少接受1个参数[Python 3]

2024-06-23 18:44:29 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我不断得到相同的错误,尽管我重新检查了超过15分钟。关于你的信息,我在sublime文本上运行了它,错误如下:

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

代码如下所示:

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

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

    def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()

    def read_odometer(self):
        print("This car has " + str(self.odometer_reading) + " miles on it.")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

    def increment_odometer(self, miles):
        self.odometer_reading += miles

class ElectricCar(Car):
    """Represent aspects of a car, specific to electric vehicles."""

    def __init__(self, make, model, year):
        """Initialize attributes of the parent class."""
        super().__init__(make, model, year)

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

Tags: nameselfmakemodelinitdefcaryear
1条回答
网友
1楼 · 发布于 2024-06-23 18:44:29

这里的问题是StackOverflow上的一个相当大的问题。但我会解释你是如何错误地使用super()。您正在使用所谓的Old Style classes,同时尝试使用super()新样式类继承自^{},可以在Python 2.2及以上版本中使用(Python 3专门使用新样式类

您的Car类声明应该如下所示->class Car(object):Car继承自object内置的),您的super调用具有对象所在的类,并且self作为参数传入:

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

现在,如果我们打印出对象的类型是:

>>> print type(my_tesla)
<class '__main__.ElectricCar'>    

我们可以看到它的类型是ElectricCar

为什么这一切都很重要?这些风格之间有一些关键的区别。在旧样式中,类及其为实例化定义的对象属于不同的类型。在旧式类中,实例总是instance类型,而不管它们的类是什么。对于新样式的类,实例通常将与其类共享相同的类型。示例:

旧式

>>> class MyClass:
    pass
>>> print type(MyClass)
>>> print type(MyClass())
<type 'classobj'>
<type 'instance'>

新风格->

>>> class MyClass(object):
    pass
>>> print type(MyClass)
>>> print type(MyClass())
<type 'type'>
<class '__main__.MyClass'>

请参阅Python关于^{}的官方文档

相关问题 更多 >

    热门问题