python, inheritance, super() method
我刚接触过python,我有下面的代码,但我无法使用:这是继承,我有一个循环基类,我在一个
我知道这个问题在
我知道
我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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) +"} " 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) +"} " return text shapeOne = Point(10,10) print( shapeOne.ToString() ) # this works fine shapeTwo = Circle(4, 6, 12) print( shapeTwo.ToString() ) # does not work |
您需要在
1 2 | text = super(Circle, self).ToString() +"{radius =" + str(self.radius) +"} " |
随着这种变化,输出是:
1 2 3 | >>> print( shapeTwo.ToString() ) {x:0.0, y:0.0} {radius = 12} |
请注意,您在您的
1 2 3 4 | def __init__(self, x, y, radius): super(Circle, self).__init__(x ,y) self.radius = radius print("circle constructor") |
然后输出变成:
1 2 3 4 5 6 | >>> shapeTwo = Circle(4, 6, 12) point constructor circle constructor >>> print( shapeTwo.ToString() ) {x:4, y:6} {radius = 12} |