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

Inheritance in python: “super() takes at least 1 argument (0 given)”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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)

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

Traceback (most recent call last):
File"/home/sumeedha/PycharmProjects/Basics/classes.py", line 50, in shuttle=SpaceShuttle(2,3,10)
File"/home/sumeedha/PycharmProjects/Basics/classes.py", line 21, in init
super().init(x, y)
TypeError: super() takes at least 1 argument (0 given)


您运行的是python 2,而super()的第一个参数type并不像python 3那样是可选的。https://docs.python.org/2.7/library/functions.html超级

您需要这样给super()打电话:

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