Python

Contributed by Chris Rathman

Shape class (modShape.py)

class Shape:

   # constructor
   def __init__(self, initx, inity):
      self.moveTo(initx, inity)

   # accessors for x & y
   def getX(self):
      return self.x
   def getY(self):
      return self.y
   def setX(self, newx):
      self.x = newx
   def setY(self, newy):
      self.y = newy

   # move the shape position
   def moveTo(self, newx, newy):
      self.setX(newx)
      self.setY(newy)
   def rMoveTo(self, deltax, deltay):
      self.moveTo(self.getX() + deltax, self.getY() + deltay)

   # abstract draw method
   def draw(self):
      pass

Rectangle class (modRectangle.py)

from modShape import Shape

class Rectangle(Shape):

   # constructor
   def __init__(self, initx, inity, initwidth, initheight):
      Shape.__init__(self, initx, inity)
      self.setWidth(initwidth)
      self.setHeight(initheight)

   # accessors for width & height
   def getWidth(self):
      return self.width
   def getHeight(self):
      return self.height
   def setWidth(self, newwidth):
      self.width = newwidth
   def setHeight(self, newheight):
      self.height = newheight

   # draw the rectangle
   def draw(self):
      print "Drawing a Rectangle at:(%d,%d), radius %d, width %d" % \
         (self.getX(), self.getY(), self.getWidth(), self.getHeight())

Circle class (modCircle.py)

from modShape import Shape

class Circle(Shape):

   # constructor
   def __init__(self, initx, inity, initradius):
      Shape.__init__(self, initx, inity)
      self.setRadius(initradius)

   # accessors for the radius
   def getRadius(self):
      return self.radius
   def setRadius(self, newradius):
      self.radius = newradius

   # draw the circle
   def draw(self):
      print "Drawing a Circle at:(%d,%d), radius %d" % \
         (self.getX(), self.getY(), self.getRadius())

Polymorphism test (modPolymorph.py)

from modShape import Shape
from modRectangle import Rectangle
from modCircle import Circle

def tryMe():

   # set up lists to hold the shapes
   scribble = [Rectangle(10, 20, 5, 6), Circle(15, 25, 8)]

   # iterate through the lists and handle shapes polymorphically
   for each in scribble:
      each.draw()
      each.rMoveTo(100, 100)
      each.draw()

   # call a rectangle specific instance
   arec = Rectangle(0, 0, 15, 15)
   arec.setWidth(30)
   arec.draw()

tryMe()

Output

Drawing a Rectangle at:(10,20), radius 5, width 6
Drawing a Rectangle at:(110,120), radius 5, width 6
Drawing a Circle at:(15,25), radius 8
Drawing a Circle at:(115,125), radius 8
Drawing a Rectangle at:(0,0), radius 30, width 15

Chris Rathman / Chris.Rathman@tx.rr.com