Created
June 21, 2012 10:02
-
-
Save edouardp/2964960 to your computer and use it in GitHub Desktop.
Still can't figure out what a visitor is in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -- Shapes ------------------------------------------------------------------- | |
class Square: | |
def __init__(self, side_length, color): | |
self.name = 'square' | |
self.side_length = side_length | |
self.color = color | |
class Circle: | |
def __init__(self, radius, color): | |
self.name = 'circle' | |
self.radius = radius | |
self.color = color | |
class Triangle: | |
def __init__(self, side_length, color): | |
self.name = 'triangle' | |
self.side_length = side_length | |
self.color = color | |
square = Square(1, 'red') | |
circle = Circle(2, 'red') | |
triangle = Triangle(3, 'blue') | |
shapes = [square, circle, triangle] | |
# -- Visitor Functions -------------------------------------------------------- | |
# | |
# Name is just shape.name | |
name_fn = lambda x: x.name | |
# Colours are mapped to RGB | |
colour_mapping = {'red': '#f00', 'blue': '#00f'} | |
colour_fn = lambda x: color_mapping[x.color] | |
# Size is defined differently per shape | |
side_fn = lambda x: 'side length = {0}'.format(x.side_length) | |
radius_fn = lambda x: 'radius = {0}'.format(x.radius) | |
size_mapping = {Square: side_fn, Circle: radius_fn, Triangle: side_fn} | |
size_fn = lambda x: size_mapping[x.__class__](x) | |
# Wrap them into one function | |
visitor = lambda x: name_fn(x) + ' (' + color_fn(x) + ', ' + size_fn(x) + ')' | |
# And interate through the list | |
[visitor(shape) for shape in shapes] | |
# Outputs | |
['square (#f00, side length = 1)', | |
'circle (#f00, radius = 2)', | |
'triangle (#00f, side length = 3)'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment