gpt4 book ai didi

Python类-- super 变量

转载 作者:太空狗 更新时间:2023-10-29 20:38:15 24 4
gpt4 key购买 nike

由于某种原因,下面的代码给我一个错误,有人能告诉我问题出在哪里吗..

基本上,我创建了 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)

最佳答案

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

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

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

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

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

我还建议去掉续行,参见 Maximum Line Length section of PEP 8了解解决此问题的推荐方法。

关于Python类-- super 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10838596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com