2016-07-15 43 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