Classes
Larry Hudson
orgnut at yahoo.com
Sun Nov 2 17:03:19 EST 2014
On 11/02/2014 01:50 AM, Denis McMahon wrote:
[snip]
> 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.
>
Why do you want to instantiate a Square with two parameters? You only need one -- side. I
agree that since you are inheriting from Rectangle you need to keep the length and width
attributes to allow the get/set of length/width, so you do need to override the Rectangle set
methods. Consider this version:
# ------ <code> ---------
class Square(Rectangle):
def __init__(self, side):
self.set_side(side)
def get_side(self):
return self.length # or width
def set_side(self, side):
self.length = self.width = side
def set_width(self, width):
self.set_side(width)
def set_length(self, length):
self.set_side(length)
# ------ </code> --------
This also eliminates the need for your exception. Of course, it still allows someone to
directly change either the length or width -- but since "we are all consenting adults here",
anyone who does this should know the consequences. ;-)
-=- Larry -=-
More information about the Python-list
mailing list