实现Square和Triangle类作为Polygon类的子类

时间:2016-07-15 20:55:54

标签: python

它会重载构造函数方法init,因此它只需要一个参数(边长)并覆盖计算区域的方法区域。我想出了这个程序,但它一直在说"未定义名称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

1 个答案:

答案 0 :(得分: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