python,继承,super()方法

时间:2012-12-29 23:18:48

标签: python inheritance super

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

1 个答案:

答案 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}
相关问题