python中的继承:“ super()至少接受1个参数(给定0个)”

时间:2018-07-06 06:30:02

标签: python-2.7 inheritance

import math

class Rocket(object):

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def move_up(self):
        self.y += 1

    def move_rocket(self, x_inc=0, y_inc=1):
        """move rocket by default move in upward direction by 1
        """
        self.x += x_inc
        self.y += y_inc

    def get_distance(self, other_Rocket):
        """calculates distance between current and other rocket
        """            
        return(math.sqrt(((self.x - other_Rocket.x)**2) + (self.y - other_Rocket.y)**2))


class SpaceShuttle(Rocket):

    def __init__(self, x=0, y=0, flights_completed=0):
        super().__init__(x, y)
        self.flights_completed = flights_completed

shuttle=SpaceShuttle(2, 3, 10)

print(shuttle)

在上面的代码中,派生类给出以下错误:

  

回溯(最近通话最近):     文件“ /home/sumeedha/PycharmProjects/Basics/classes.py”,第50行,位于Shuttle = SpaceShuttle(2,3,10)
     init 中的文件“ /home/sumeedha/PycharmProjects/Basics/classes.py”,第21行       super()。初始化(x,y)   TypeError:super()至少接受1个参数(给定0个参数)

1 个答案:

答案 0 :(得分:2)

您正在运行Python 2,而super()的第一个参数type与Python 3一样不是可选的。 https://docs.python.org/2.7/library/functions.html#super

您需要像这样致电super()

super(SpaceShuttle, self).__init__(x, y)