2012-12-29 59 views
1

我是新来的python,我有下面的代码,我只是无法去工作: - 这是继承,我有一个圆形基类,我继承了这个一个circle类(这里只是单一的继承)。python,inheritance,super()方法

我理解的问题是circle类中ToString()函数中,具体的线路,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

您需要在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} 
+0

非常感谢这一步,但不是想要的结果,所以我觉得我已经做了别的事情错在这里(!)。我现在得到这 - 点构造 {X:10,Y:10} 圈构造 {X:0.0,Y:0.0} {半径= 12} – user1937226

+0

当我的圆目的是,shapeTwo =圈(4, 6,12) – user1937226

+0

所以我应该问,我如何通过从点到点的x,y点? – user1937226