Skip to content

Instantly share code, notes, and snippets.

@raheemazeezabiodun
Last active September 19, 2019 20:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raheemazeezabiodun/0970ea4dd6479522ec9207d8f2d1339c to your computer and use it in GitHub Desktop.
Save raheemazeezabiodun/0970ea4dd6479522ec9207d8f2d1339c to your computer and use it in GitHub Desktop.
A way of dispatching action based on type in Python.
"""
This demonstrates how to use singledispatch for dispatching on type
We want to draw each based on the type. Typically, we can use if else statement to check the type
then call the function that does draw the shape, however, we will keep having multiple if elif statement.
This is just another pythonic way of doing it
"""
from functools import singledispatch
class Shape:
def __init__(self, solid):
self.solid = solid
class Circle(Shape):
def __init__(self, center, radius, *args, **kwargs):
super().__init__(*args, **kwargs)
self.center = center
self.radius = radius
class Parallelogram(Shape):
def __init__(self, pa, pb, pc, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pa = pa
self.pb = pb
self.pc = pc
class Triangle(Shape):
def __init__(self, pa, pb, pc, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pa = pa
self.pb = pb
self.pc = pc
@singledispatch
def draw(shape):
raise TypeError("Don't know how to draw {!r}".format(shape))
@draw.register(Circle)
def draw_circle(shape):
print("\u25CF" if shape.solid else "\u25A1")
@draw.register(Parallelogram)
def draw_parallelogram(shape):
print("\u25B0" if shape.solid else "\u25B1")
@draw.register(Triangle)
def draw_triangle(shape):
print("\u25B2" if shape.solid else "\u25B3")
def main():
shapes = [Circle(center=(0, 0), radius=5, solid=False),
Parallelogram(pa=(0, 0), pb=(2, 0), pc=(1, 1), solid=False),
Triangle(pa=(0, 0), pb=(1, 2), pc=(2, 0), solid=True)
]
for shape in shapes:
draw(shape)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment