8

下面的代码由于某种原因给了我一个错误,有人可以告诉我会是什么问题..

基本上,我创建了 2 个类 Point & Circle..The circle 试图继承 Point 类。

Code:


class Point():

    x = 0.0
    y = 0.0

    def __init__(self, x, y):
        self.x = x
        self.y = y
        print("Point constructor")

    def ToString(self):
        return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"

class Circle(Point):
    radius = 0.0

    def __init__(self, x, y, radius):
        super(Point,self).__init__(x,y)
        self.radius = radius
        print("Circle constructor")

    def ToString(self):
        return super().ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"


if __name__=='__main__':
        newpoint = Point(10,20)
        newcircle = Circle(10,20,0)

错误:

C:\Python27>python Point.py
Point constructor
Traceback (most recent call last):
  File "Point.py", line 29, in <module>
    newcircle = Circle(10,20,0)
  File "Point.py", line 18, in __init__
    super().__init__(x,y)
TypeError: super() takes at least 1 argument (0 given)
4

3 回答 3

13

看起来您可能已经修复了原始错误,这是由super().__init__(x,y)错误消息指示引起的,尽管您的修复有点不正确,而不是super(Point, self)来自Circle您应该使用的类super(Circle, self)

请注意,在's方法中还有另一个地方调用super()不正确:CircleToString()

        return super().ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"

这是 Python 3 上的有效代码,但在 Python 2 上super()需要参数,将其重写如下:

        return super(Circle, self).ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"

我还建议摆脱续行,请参阅PEP 8 的最大行长部分以了解修复此问题的推荐方法。

于 2012-05-31T17:54:03.003 回答
7

super(..)只接受新式课程。要修复它,请从object. 像这样:

class Point(object):

使用 super(..) 的正确方法是:

super(Circle,self).__init__(x,y)
于 2012-05-31T17:57:59.627 回答
0
class Point(object):

x = 0.0
y = 0.0

def __init__(self, x, y):
    self.x = x
    self.y = y
    print("Point constructor")

def ToString(self):
    return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"

class Circle(Point,object):
radius = 0.0

def __init__(self, x, y, radius):
    super(Circle,self).__init__(x,y)
    self.radius = radius
    print("Circle constructor")

def ToString(self):
    return super(Circle, self).ToString() + \
           ",{RADIUS=" + str(self.radius) + "}"


if __name__=='__main__':     
    newpoint = Point(10,20)    
    newcircle = Circle(10,20,0)
于 2017-03-31T13:22:24.257 回答