python - Implement classes Square and Triangle as subclasses of class Polygon -
it overload constructor method init takes 1 argument(side length) , override method area computes area. came program, keeps saying "undefined name polygon".
class square(polygon): 'square class' def __init__(self, s): 'constructor initializes side length of square' polygon.__init__(self, 4, s) def area(self): 'returns square area' return self.s**2 math import sqrt class triangle(polygon): def __init__(self, s): 'constructor initializes side length of equilateral triangle' polygon.__init__(self, 3, s) def area(self): 'returns triangle area' return sqrt(3)*self.s**2/4
if want inherit polygon
, have define before define other classes inherit it.
class polygon: def __init__(self): pass def area(self): raise notimplemented class square(polygon): 'square class' def __init__(self, s): 'constructor initializes side length of square' polygon.__init__(self, 4, s) def area(self): 'returns square area' return self.s**2 math import sqrt class triangle(polygon): def __init__(self, s): 'constructor initializes side length of equilateral triangle' polygon.__init__(self, 3, s) def area(self): 'returns triangle area' return sqrt(3)*self.s**2/4
Comments
Post a Comment