Contributed by Rico Schiekel
Here is a slightly improved version of the python example.
IMHO it's more pythonic and more simpler than the original from Monty Stein.
#!/usr/bin/env python
#
# vim:syntax=python:sw=4:ts=4:expandtab
class Shape(object):
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
raise NotImplementedError('draw() not implemented!')
def move_to(self, newx, newy):
self.x = newx
self.y = newy
def relative_move(self, dx, dy):
self.x += dx
self.y += dy
class Rectangle(Shape):
def __init__(self, x, y, width, height):
super(Rectangle, self).__init__(x, y)
self.width = width
self.height = height
def draw(self):
print 'drawing rectangle at (%d,%d) with width %d, height %d' % \
(self.x, self.y, self.width, self.height)
class Circle(Shape):
def __init__(self, x, y, r):
super(Circle, self).__init__(x, y)
self.radius = r
def draw(self):
print 'drawing circle at (%d,%d) with radius %d' % \
(self.x, self.y, self.radius)
if __name__ == '__main__':
# using shapes polymorphically
for shape in (Rectangle(10, 20, 5, 6), Circle(15, 25, 8)):
shape.draw()
shape.relative_move(100, 100)
shape.draw()
# access a rectangle specific function
rect = Rectangle(0, 0, 15, 15)
rect.width = 30
rect.draw()
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