Dictionary example:
favourite = 3
numbers = { 1:'one', 2:'two', 3:'three', 4:'four', 5:'five' }
print("Your favourite number is %s" % numbers[favourite])
Not sure that there’s such a thing as a simple polymorphism example, but the animals one here should give you an idea.
I use polymorphism in my mesh generation functions for Primstar. I have a complex base class that uses get_vector(u, v) to convert UV co-ordinates into a 3D vector during the mesh generation. So by creating subclasses and just changing that one function in the class, I get new 3D shapes that all have the same function to call to generate them. So the actual defination for a new shape looks like this:
class AddUVPlane(bpy.types.Operator, AddUVBase):
mesh_name = "Plane"
bl_idname = "mesh.uv_shape_plane_add"
bl_label = "Add plane UV shape"
def get_vector(self, u, v):
return (u - 0.5, v - 0.5, 0.0)
That avoids having all the shapes in one class and lots of if elif to select the correct vector generation. All the complex stuff is in the AddUVBase class, and I’m not risking introducing new bugs into tried and tested code if I want to add a new shape, say a cylinder…
class AddUVCylinder(bpy.types.Operator, AddUVBase):
mesh_name = "Cylinder"
bl_idname = "mesh.uv_shape_cylinder_add"
bl_label = "Add cylinder UV shape"
wrap_u = True
def get_vector(self, u, v):
a = pi + 2 * pi * u
x = sin(a) / 2.0
y = -cos(a) / 2.0
return (x, y, v - 0.5)
wrap_u is also used by the mesh generation, to add a seam and close the loop in the u direction… I’m sure you can see how
if shape is plane: …
elif shape is cylinder: …
at various points in the code is going to get awfully messy pretty quickly.