3

我是 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
4

1 回答 1

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}
于 2012-12-29T23:21:12.230 回答