2015-11-19 52 views
1

我必須使用super()方法創建一個從Rectangle類派生的Square類。我一直在使用其他方法,當我在派生方法使用它,我只能把在python中使用super()方法

super().__init__() 

但是當我用它爲方形方法我得到一個錯誤

TypeError: __init__() missing 4 required positional arguments: 'x', 'y', 'width', and 'height' 

會在哪裏我把4個參數,如果我已經把自己的初始化,它只需要3個方塊?

我不知道它是否重要,但Rectangle類是從另一個類Polygon派生的,可能是我缺少的東西? 下面的代碼:

class Rectangle(Polygon): 
    def __init__(self, x, y, width, height): 
     super().__init__() 
     self.add_point((x, y)) 
     self.add_point((x + width, y)) 
     self.add_point((x + width, y + height)) 
     self.add_point((x, y + height)) 


class Square(Rectangle): 
    def __init__(self,x,y,length, width): 
     super().__init__() 
     self.add_point((x,y)) 
     self.add_point((x+length, y)) 
     self.add_point((x+length, y+ length)) 
     self.add_point((x, y+length)) 

回答

2

當你調用super().__init__()一定要適當的參數傳遞給它。

super().__init__(x, y, width, height)

解釋道:Square背景下,呼籲super().__init__()呼籲Rectangle.__init__,因爲它是子類。然後Rectangle的__init__調用super.__init__()這是調用Polygon.__init__()這些調用的所有都需要具有正在調用的init函數的正確參數。

+0

但一個正方形只需要3個參數,所以我怎麼會傳遞4個參數爲矩形。 –

+0

沒錯。一個正方形具有_same長度和寬度_。你可以調用'Square(x,y,width)',那麼你可以調用'super().__ init __(x,y,width,width)' –

+0

另外,在源文件中,Square有4個參數。 –

相關問題