Python类——超变量

Python类——超变量,python,Python,下面的代码出于某种原因给了我一个错误,有人能告诉我会出现什么问题吗 基本上,我创建了两个类Point和Circle。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)

下面的代码出于某种原因给了我一个错误,有人能告诉我会出现什么问题吗

基本上,我创建了两个类Point和Circle。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)
C:\Python27>pythonpoint.py
点构造函数
回溯(最近一次呼叫最后一次):
文件“Point.py”,第29行,在
新圆=圆(10,20,0)
文件“Point.py”,第18行,在_init中__
super().\uuuu init\uuuu(x,y)
TypeError:super()至少接受1个参数(给定0个)

看起来您可能已经修复了由
super()引起的原始错误。正如错误消息所示,尽管您的修复有点不正确,但您应该使用
super(Circle,self)
类中的
super(Point,self)
,而不是
Circle
中的
super(Circle,self)

请注意,在
圆圈
ToString()方法中,还有另一个地方错误地调用了
super()

        return super().ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"
这是Python3上的有效代码,但在Python2上
super()
需要参数,请按以下方式重写此代码:

        return super(Circle, self).ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"
我还建议取消行延续,请参阅,以获取修复此问题的建议方法。

super(…)
只接受新样式的类。若要修复它,请从
对象
扩展点类。像这样:

class Point(object):
此外,使用super(..)的正确方法如下:


错误消息明确指出错误不是来自该行。@Markransem-没错!谢谢。您应该建议
ToString()
根本不是正确的想法,这就是
\uuuu str\uuuuu
的目的。您是否对源代码进行了一些编辑?您的
init
调用最初是这样的吗?
ToString
,哦!我的眼睛在流血
super(Circle,self).__init__(x,y)
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)