use*_*226 3 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
Run Code Online (Sandbox Code Playgroud)
你需要传入这个Circle类:
text = super(Circle, self).ToString() + "{radius = " + str(self.radius) + "}\n"
Run Code Online (Sandbox Code Playgroud)
super()将查看第一个参数的基类以查找下一个ToString()方法,并且Point没有该方法的父级.
通过该更改,输出为:
>>> print( shapeTwo.ToString() )
{x:0.0, y:0.0}
{radius = 12}
Run Code Online (Sandbox Code Playgroud)
请注意,你犯了同样的错误__init__; 你根本没有称之为继承__init__.这有效:
def __init__(self, x, y, radius):
super(Circle, self).__init__(x ,y)
self.radius = radius
print("circle constructor")
Run Code Online (Sandbox Code Playgroud)
然后输出变为:
>>> shapeTwo = Circle(4, 6, 12)
point constructor
circle constructor
>>> print( shapeTwo.ToString() )
{x:4, y:6}
{radius = 12}
Run Code Online (Sandbox Code Playgroud)