[Edu-sig] Gutless classes
Kirby Urner
urnerk at qwest.net
Fri Sep 9 21:14:32 CEST 2005
Here's another example of defining a class by stuffing an empty shell with
externally defined methods. It's really just another way of organizing
code, perhaps to bring out some aspect of the knowledge domain.
Here, we're in geometry, talking about how a given polyhedron (tetrahedron,
cube, you name it), when scaled, changes its edge, surface area, and volume.
The scale factor is here applied directly to the edge, i.e. a scale factor
of 3 trebles every edge in size (like zooming in by 3x). This has 2nd and
3rd powering side effects on area and volume, as these functions make clear:
IDLE 1.1
>>> class Shape (object): pass
>>> def build(self, edge = 1, area = 1, volume = 1):
self.edge = edge
self.surface = area
self.volume = volume
>>> def scale(self, factor):
self.edge *= factor
self.surface *= factor**2
self.volume *= factor**3
>>> def reporter(self):
return "Shape <%s, %s, %s>" % (self.edge, self.surface,
self.volume)
>>> Shape.__init__ = build
>>> Shape.__mul__ = scale
>>> Shape.__repr__ = reporter
>>> myshape = Shape()
>>> myshape
Shape <1, 1, 1>
>>> myshape * 3
>>> myshape
Shape <3, 9, 27>
>>> myshape * 0.125
>>> myshape
Shape <0.375, 0.140625, 0.052734375>
Kirby
More information about the Edu-sig
mailing list