I'm using an object-oriented approach with inheritance to solve a problem, and I'm wondering how to apply 'Duck Typing' principles to this problem.
I have a class BoxOfShapes
which would be instantiated with a list of Shapes
( Circle
, Square
and Rectangle
)
import numpy as np
class Shape(object):
def __init__(self,area):
self.area = area;
def dimStr(self):
return 'area: %s' % str(self.area)
def __repr__(self):
return '%s, %s' % (self.__class__.__name__, self.dimStr()) + ';'
class Circle(Shape):
def __init__(self,radius):
self.radius = radius
def dimStr(self):
return 'radius %s' % str(self.radius)
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def dimStr(self):
return '%s x %s' % (str(self.width), str(self.height))
class Square(Rectangle):
def __init__(self, side):
self.width = side
self.height = side
class BoxOfShapes(object):
def __init__(self, elements):
self.elements = elements
def __repr__(self):
pass
listOfShapes = [Rectangle(10,13),Rectangle(9,5),Circle(12),Circle(8),Circle(36),Square(10)]
myBox = BoxOfShapes(listOfShapes)
print myBox
So lets look at the __repr__()
method of BoxOfShapes
. From what I understand, a duck-typing implementation would be something like,
def __repr__(self):
return str(self.elements)
because this says 'I don't care what elements I have as long as they implement __str__()
or __repr__()
. The output of this is
>>> print myBox
[Rectangle, 10 x 13;, Rectangle, 9 x 5;, Circle, radius 12;, Circle, radius 8;, Circle, radius 36;, Square, 10 x 10;]
Lets say I want a more human-readable output from BoxOfShapes
- I know all the shapes are of certain types, so it would be nice to categorize, them like so:
def __repr__(self):
circles = [ el.dimStr() for el in self.elements if isinstance(el, Circle)]
squares = [ el.dimStr() for el in self.elements if isinstance(el, Square)]
rectangles = [el.dimStr() for el in self.elements if (isinstance(el, Rectangle) and not isinstance(el, Square)) ]
return 'Box of Shapes; Circles: %s, Squares: %s, Rectangles: %s;' % ( str(circles), str(squares), str(rectangles))
The output of this is,
>>> print myBox
Box of Shapes; Circles: ['radius 12', 'radius 8', 'radius 36'], Squares: ['10 x 10'], Rectangles: ['10 x 13', '9 x 5'];
which is easier to read, but I am no longer using duck-typing and now I have to change my definition of BoxOfShapes
any time I think up a new kind of shape.
My question is (how) would one apply duck-typing in this kind of scenario?