3

私はPythonを初めて使用します。以下のコードを使用すると、動作しなくなります。-これは継承です。サークル基本クラスがあり、circleクラス内でこれを継承します(ここでは単一の継承のみ)。

問題はクラス内のToString()関数、特に 少なくとも1つの引数を必要とする行にあることを理解していますが、次のようになります。circletext = 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 に答える