2016-07-15 42 views
-1

它將重載構造函數方法init,因此它只接受一個參數(邊長),並將覆蓋計算區域的方法區域。我想出了這個程序,但它一直說「未定義名稱Polygon」。將類Square和Triangle作爲類Polygon的子類實現

class Square(Polygon): 
    'square class' 

    def __init__(self, s): 
     'constructor that initializes the side length of a square' 
     Polygon.__init__(self, 4, s) 

    def area(self): 
     'returns square area' 
     return self.s**2 

from math import sqrt 
class Triangle(Polygon): 
    def __init__(self, s): 
     'constructor that initializes the side length of an equilateral triangle' 
     Polygon.__init__(self, 3, s) 

    def area(self): 
     'returns triangle area' 
     return sqrt(3)*self.s**2/4 
+0

您是否定義了一個'''Polygon''類(在另外兩個之前)? – wwii

+0

我不明白。我對這件事還是有點新鮮感。 – user6523697

回答

0

如果你想從Polygon繼承,你有你定義一個繼承自它的其他類之前定義它。

class Polygon: 
    def __init__(self): 
     pass 
    def area(self): 
     raise NotImplemented 

class Square(Polygon): 
    'square class' 

    def __init__(self, s): 
     'constructor that initializes the side length of a square' 
     Polygon.__init__(self, 4, s) 

    def area(self): 
     'returns square area' 
     return self.s**2 

from math import sqrt 
class Triangle(Polygon): 
    def __init__(self, s): 
     'constructor that initializes the side length of an equilateral triangle' 
     Polygon.__init__(self, 3, s) 

    def area(self): 
     'returns triangle area' 
     return sqrt(3)*self.s**2/4