我是python的新手,我有下面的代码,我无法开始工作: -
这是继承,我有一个圆基类,我在circle
类中继承了它(这里只是单继承)。
我理解问题出在ToString()
类的circle
函数中,特别是行text = super(Point, self).ToString() +..
这需要至少一个参数,但我得到了这个:
AttributeError: 'super' object has no attribute 'ToString'
我知道super
没有ToString
属性,但Point
类没有 -
我的代码:
class Point(object):
x = 0.0
y = 0.0
# point class constructor
def __init__(self, x, y):
self.x = x
self.y = y
print("point constructor")
def ToString(self):
text = "{x:" + str(self.x) + ", y:" + str(self.y) + "}\n"
return text
class Circle(Point):
radius = 0.0
# circle class constructor
def __init__(self, x, y, radius):
super(Point, self) #super().__init__(x,y)
self.radius = radius
print("circle constructor")
def ToString(self):
text = super(Point, self).ToString() + "{radius = " + str(self.radius) + "}\n"
return text
shapeOne = Point(10,10)
print( shapeOne.ToString() ) # this works fine
shapeTwo = Circle(4, 6, 12)
print( shapeTwo.ToString() ) # does not work
答案 0 :(得分:5)
您需要传递Circle
课程:
text = super(Circle, self).ToString() + "{radius = " + str(self.radius) + "}\n"
super()
将查看第一个参数的基类以查找下一个ToString()
方法,而Point
没有父方法使用该方法。
通过该更改,输出为:
>>> print( shapeTwo.ToString() )
{x:0.0, y:0.0}
{radius = 12}
请注意,您在__init__
中犯了同样的错误;你根本没有调用继承的__init__
。这有效:
def __init__(self, x, y, radius):
super(Circle, self).__init__(x ,y)
self.radius = radius
print("circle constructor")
然后输出变为:
>>> shapeTwo = Circle(4, 6, 12)
point constructor
circle constructor
>>> print( shapeTwo.ToString() )
{x:4, y:6}
{radius = 12}