I recently had a coding challenge where I theorised that a concise solution could be found if functions could be treated as elements and packaged into lists / arrays or even dictionaries. Perhaps I came across an article discussing this feature — hence the intuition — but I never really had the chance to try it out before then.
Imagine we wanted to create a simple list of functions that returns the area or volume of the object . The index of the function-element represents the object’s dimension, and the single argument to be passed to it represents the length of a side of the object.
So in the example below in line 1, if we were looking for the volume of a cube with a side length of 2 units, the volume would be 8 cubic units as shown in line 5.
Dictionaries would also work, where instead of using the indices, we provide key as a name of the function-value. The dictionary area provides the area of a square or equilateral triangle, such that the latter could be found via the code on line 7 above.
Then I had another question. Could we simply use object-oriented syntax in such a case — i.e.class.method — which would have been natural given that is how functions are organised as methods for classes. In Python, certain libraries such as Pandas have made this common to the point that it just comes to mind, rightly or wrongly. Unfortunately, as the attribute error in line 13 onward shows, native Python does not support such syntax.
Another day of discoveries.