Classes
Denis McMahon
denismfmcmahon at gmail.com
Sun Nov 2 10:50:37 CET 2014
On Sat, 01 Nov 2014 12:42:10 -0400, Seymore4Head wrote:
> OK Maybe I misunderstood the question.
>
> My answer to you then is ......I don't know. I will have to think about
> it some more.
The question (I thought) was to write a class for Square that inherited a
class Rectangle but imposed on it the additional constraints of a square
over a rectangle, namely that length == width.
To do this, you need to override the inherited methods to set length and
width with new methods to set length and width as follows:
when setting length, also set width equal to length.
when setting width, also set length equal to width.
For bonus points, if your constructor accepts width and length parameters
(from the Rectangle constructor) then detect if they are different and
raise a suitable error.
from math import sqrt
class SquareGeometryError(Exception):
"""The parameters create an illegal geometry for a square"""
pass
class Rectangle:
def __init__(self,length,width):
self.length=length
self.width=width
def area(self):
return self.length*self.width
def perimeter(self):
return 2*self.length+2*self.width
def diagonal(self):
return sqrt(self.length*self.length+self.width*self.width)
def get_width(self):
return self.width
def get_length(self):
return self.length
def set_width(self, width):
self.width = width
def set_length(self, length):
self.length = length
class Square(Rectangle):
_def _init__(self, length, width):
if not length == width:
raise SquareGeometryError("Length must equal width")
self.length = length # or width
self.width = length # or width
def set_width(self, width):
self.length = width
self.width = width
def set_length(self, length):
self.length = length
self.width = length
Note that to make my square, I only need to over-ride those rectangle
methods which allow the setting of length and width to enforce squareness
upon the square. All the other methods of rectangle will work equally
well for the square.
--
Denis McMahon, denismfmcmahon at gmail.com
More information about the Python-list
mailing list