In Python, is there anyway to pass a method to a higher order function, as you would if passing a regular function?
For example, let's say I have a string, "str", and depending on some condition, "cond", I want to apply some arbitrary method, "meth", to the string and return it. In code:
def func(str, meth, cond):
...
if cond:
str.meth()
...
Now, I know the above doesn't work. I also know that I could write something like:
def func(str, meth, cond):
...
if cond:
str = meth
...
and pass the object and method I want to execute to func like this: func(str, str.capitalize(), cond). The problem with the above is that:
- The above code doesn't make the intention of the function clear.
If I, for example, want to modify "str" in anyway before the application of the method, then I end up with an incorrect result. Consider:
def func(str, meth, cond): ... str += "a" ... if cond: str = meth ...
will not work as intended.
So, returning to the beginning: is there anyway to accomplish what I want? Or am I approaching this from the wrong direction altogether?