【问题标题】:Error trying to use super().__init__尝试使用 super().__init__ 时出错
【发布时间】:2017-02-23 06:31:03
【问题描述】:

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

【问题讨论】:

  • 这是有效的 Python 3 代码,因此如果遇到问题,您可能正在使用 Python 2。
  • ^ 这是有效的 Python 代码,因此您可能使用的是“以前称为 python 的版本”...

标签: python inheritance init super


【解决方案1】:

您运行的是 Python 2,而不是 Python 3。Python 2's super 至少需要一个参数(定义此方法的类型),通常需要两个参数(当前类型和 self)。只有Python 3's super 可以不带参数调用。

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

import sys

print(sys.version_info)

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

class ElectricCar(Car):
    pass

并且它的行为相同(通过避免不必要的拦截和__init__ 的委托,它会运行得稍微快一点,仅此而已)。

【讨论】:

  • 此外 - 在 Python 2 中,类应始终从 object 继承 - 否则访问属性的机制很少 - super 包括在内,将不起作用。
  • @jsbueno:Yar。您可以明确地这样做,或者在文件顶部附近添加__metaclass__ = type(在定义任何类之前)以使其中定义的所有类都隐式地成为新样式,即使在 Python 2 上也是如此(Python 3 忽略 __metaclass__,所以有那里没有成本)。但在这种情况下,问题在于 OP 认为他们在 Py3 上,而实际上在 Py2 上,并且运行正确版本的 Python 将消除该问题。
  • 这确实是问题所在。感谢您的帮助。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2017-07-18
    • 2017-02-08
    • 2018-12-02
    • 2020-09-07
    • 2021-09-14
    相关资源
    最近更新 更多