[Edu-sig] Design patterns

Scott David Daniels Scott.Daniels at Acm.Org
Sat Aug 20 04:31:27 CEST 2005


Kirby Urner wrote:
> I’ve been thinking that a good way to introduce program design might involve
> objects of type Triangle, i.e. instances of the Triangle class.

> Anyway, here's a design question:  do we want to compute the angles and
> store them as properties at the time of construction, i.e. in the init?  Or
> do we want to make getAngles() a method?  Compromise:  call _getAngles from
> the init.

Here's how to do the angles in 2.4 w/ properties:


class Triangle(object):

     def __init__(self, a,b,c):
         "Construct a triangle"
         if (c >= a + b) or (a >= b + c) or (b >= a + c):
             raise ValueError("Illegal edges: %s/%s/%s" % (a, b, c))
         self.a = a
         self.b = b
         self.c = c

     def area(self):
         "Heron's Formula"
         s = 0.5 * (self.a + self.b + self.c)
         return math.sqrt( s * (s - self.a) *
                         (s - self.b) * (s - self.c))
     @property
     def A(self):
	return math.acos((-self.a**2 + self.b**2 + self.c**2)
			 / (2.0 * self.b * self.c))
     @property
     def B(self):
	return math.acos((self.a**2 - self.b**2 + self.c**2)
			 / (2.0 * self.a * self.c))
     @property
     def C(self):
	return math.acos((self.a**2 + self.b**2 - self.c**2)
			 / (2.0 * self.a * self.b))


Now you can do:

     t = Triangle(3,4,5)
     t.c, math.degrees(t.C)
     t.a/math.sin(t.A), t.b/math.sin(t.B), t.c/math.sin(t.C)
     t.b = t.c = 3
     t.c, math.degrees(t.C)
     t.a/math.sin(t.A), t.b/math.sin(t.B), t.c/math.sin(t.C)

This takes advantage of the fact that property with a single parameter
defines only the "get value" accessor, and makes setting or deleting
the property illegal.

-- Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Edu-sig mailing list