I am having problems passing a method in a function. I have already looked at this previous post.
How do I pass a method as a parameter in Python
Here is a simple example of what I tried.
def passMethod(obj, method):
return obj.method()
passMethod('Hi', lower)
In the end I will use this to help write a function dealing with GIS (Geographic Information Systems) data. The data is like an array. I want to add a new column NAME1 to the array. The array then has a method to call the column array.NAME1.
Regards,
Alex
When you give the name
lower, that means to look up the namelowerin the global namespace. It isn’t there, because you’re looking for thelowermethod of strings (thestrclass). That is spelledstr.lower.Then, in your function,
obj.methodmeans to look up themethodattribute of theobj. It has nothing to do with the parameter namedmethod, and cannot work that way. Instead, since you have an unbound method, pass the object as theselfparameter explicitly: thus,method(obj). That gives us:Alternately, we could use a string as the name of the method to look up on the passed-in object. That looks like: