creating one of a family of classes
Darrell
news at dorb.com
Thu Dec 2 23:35:39 EST 1999
I might think of polygon as a function or factory.
All the other shapes may or may not inherit from a common base.
Here's a quick stab. That could use a comment, I guess.
import bisect, copy
class Poly:
def __init__(self):
self._shapes=[]
def addShapes(self, shapes):
for s in shapes:
self._shapes.append((s._numSides, s))
self._shapes.sort()
def __call__(self, *args):
start=bisect.bisect(self._shapes, (len(args),))
end =bisect.bisect(self._shapes, (len(args)+1,))
for x in range(start,end):
shape=self._shapes[x]
shapeI=shape[1]
cc=shapeI(args)
if cc != None:
print 'Found:', cc._name
return cc
return 0
def allSidesEqual(sides):
s1=sides[0]
for s in sides[1:]:
if s != s1:
return 0
return 1
def pairsOfSidesEqual(sides):
l=list(sides)
l.sort()
last=None
for s in l:
if last==None:
last=s
continue
if s != last:
return 0
last=None
return 1
class Shape:
def __init__(self, numSides, name, *tests):
self._name=name
self._numSides=numSides
self._tests=tests
self._sides=None
def __call__(self, sides):
for t in self._tests:
if t(sides) ==0:
return None
newShape=copy.copy(self)
newShape._sides=sides
return newShape
shapes=[Shape(4,'Square', (allSidesEqual)),\
Shape(4,'Rectangle', (pairsOfSidesEqual)),\
Shape(3,'Triangle', (allSidesEqual))]
polyFactory=Poly()
polyFactory.addShapes(shapes)
polyFactory(2,2,2,2)
polyFactory(2,2,2)
polyFactory(2,2,4,4)
#### output
poly.py
Found: Square
Found: Triangle
Found: Rectangle
--
--Darrell
"Roy Smith" <roy at endeavor.med.nyu.edu> wrote in message
news:roy-0212992011390001 at mc-as01-p60.med.nyu.edu...
> I want to have a family of classes which are all subclasses of a common
> ancestor. For the sake of a simple example, let's say I have a class
> polygon, with subclasses triangle, square, pentagon, and hexagon.
>
More information about the Python-list
mailing list