{ |one, step, back| }

The Shape Example in Python

Contributed by Monty Stein

Code for Python

File: shapes.py

#!/usr/bin/env python

class Shape:
  def __init__(self,x,y):
    """ Constructor for the class, put all init functions in shape_init """
    self.shape_init(x,y)

  def shape_init(self,x,y):
    """ The real constructor for the class, put all init functions here """
    (self.x,self.y)=(x,y)

  def draw(self):
    None  # just for completeness, must be implemented by inherited classes

  def move_to(self,newx,newy):
    (self.x,self.y)=(newx,newy)

  def relative_move(self,dx,dy):
    (self.x,self.y)=(self.x+dx,self.y+dy)


########
# Rectangles 

class Rectangle(Shape):
  """ all the stuff specific to rectangles, inherits from shape for base 
      functions
  """

  def __init__(self,x,y,width,height):
    self.shape_init(x,y);
    self.width=width
    self.height=height

  def set_width(self,newwidth):
    self.width=newwidth;
   
  def set_height(self,newheight):
    self.height=newheight;
  
  def draw(self):
    print "drawing rectangle at (%d,%d) with width %d, height %d" % \
             (self.x,self.y,self.width,self.height)
    

########
# Circles 

class Circle(Shape): 
  """ all the stuff specific to circles, inherits from shape for base 
      functions """
  def __init__(self,x,y,r):
    self.shape_init(x,y)
    self.radius=r

  def set_radius(self,newrad):
    self.radius=r

  def draw(self):
    print "drawing circle at (%d,%d) with radius %d" % \
             (self.x,self.y,self.radius)


if __name__ == "__main__":
  def DoSomethingWithShape(s):
    s.draw()
    s.relative_move(100,100)
    s.draw()

  #########
  # using shapes polymorphically
  shapes={}
  shapes[0]=Rectangle(10,20,5,6)
  shapes[1]=Circle(15,25,8)

  for i in [0,1]:
    DoSomethingWithShape(shapes[i])

  # access a rectangle specific function 
  rect=Rectangle(0,0,15,15)
  rect.set_width(30)
  rect.draw()

Output

drawing rectangle at (10,20) with width 5, height 6
drawing rectangle at (110,120) with width 5, height 6
drawing circle at (15,25) with radius 8
drawing circle at (115,125) with radius 8
drawing rectangle at (0,0) with width 30, height 15