It has just occurred to me that Python’s functional programming support may mean that polymorphism is unbelievably easier and powerful under Python.
Consider the following code:
func = getattr(class_name, ‘method_name’)
func(arguments)
You can dynamically obtain a “function object” and invoke it with arguments.
Not only do you not need to care what function you just got, you don’t even need the method names to be identical as long as you follow a convention! You can say:
func = getattr(class_name, ‘get_%s_pie’, %fruit)
func(num_of_pies)
As long as you define the “fruit string”, now my code won’t need to care what fruit your object is. You can have get_apple_pie, get_banana_pie, get_strawberry_pie, and my code won’t care! This is polymorphism at the function level, which for me is unheard of until now. C/C++/C#/Java all require object level polymorphism, but do NOT support function/method level polymorphism. With functional programming, this is now possible.
In Python, even Classes (object definitions) are “objects”. At first this was the weirdest thing I’ve heard in programming languages in a long while. But now with the functional programming methodology, this makes factory methods stupidly simple. Consider the following code:
object_class = getattr(module_name, ‘class_name’)
object = object_class(arguments)
Again, use getattr to dynamically get the “class object”, and then invoke it and create a specific object instance. This is object level polymorphism and this is unbelievably simple and elegant. Compared to the C#/Java way of:
case ‘a’:
return new a();
case ‘b’:
return new b();
etc….
With python I only have to say:
object_class = getattr(module_name, ‘a’)
object = object_class()
AMAZING!! At first I was skeptical at Python’s “elegance”, with the no-semicolon and indented code blocks, I thought it was just “pretty” rather than practical. Now I have discovered Python’s functional programming features, I am very impressed and beginning to believe the hype.