Python课程--超级变量

2024-06-11 22:44:05 发布

您现在位置:Python中文网/ 问答频道 /正文

下面这段代码由于某种原因给了我一个错误,有人能告诉我是什么问题吗。。

基本上,我创建了2个类Point&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)

Tags: pyselfreturninitdef错误classpoint
3条回答
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)

super(..)只接受新样式的类。要修复它,请从object扩展Point类。像这样:

class Point(object):

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

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

看起来您已经修复了最初的错误,正如错误消息所示,这是由super().__init__(x,y)引起的,虽然您的修复有点不正确,但是您应该使用Circle类中的super(Point, self)

注意,在CircleToString()方法内部,还有一个地方调用super()不正确:

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

这是Python3上的有效代码,但在Python2上super()需要参数,请重写如下:

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

我还建议不要使用行继续符,请参阅Maximum Line Length section of PEP 8以了解建议的修复方法。

相关问题 更多 >