【问题标题】:python super() function error?python super() 函数错误?
【发布时间】:2016-07-29 08:07:18
【问题描述】:
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() 函数有什么问题?

【问题讨论】:

  • 用你的超类的名字替换super(),即。 e. car。或者如果你想要supersuper(electricCar, self).__init__(make, model, year)
  • 您使用的是什么版本的 Python?您可以在 official docs 中看到 super() 语法。对于 Python 2,您需要将子类名称指定为类型参数。对于 Python3,你不需要
  • 如果您只是学习语言...为什么要从 6 岁 的 python 版本开始?只需从最新版本开始。只有需要 Python2 以向后兼容旧系统/库的人才能使用 Python2。

标签: python python-2.x


【解决方案1】:

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

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

您可以参考this question 了解有关 python2python3

的一般继承语法问题

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 感谢大家的帮助!
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-09-15
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2020-12-20
      相关资源
      最近更新 更多