Passing a method in python

python

Solution

When you give the name `lower`, that means to look up the name `lower` in the global namespace. It isn't there, because you're looking for the `lower` method of strings (the `str` class). That is spelled `str.lower`.

Then, in your function, `obj.method` means to look up the `method` attribute of the `obj`. It has nothing to do with the parameter named `method`, and cannot work that way. Instead, since you have an unbound method, pass the object as the `self` parameter explicitly: thus, `method(obj)`. That gives us:

def passMethod(obj, method):
    return method(obj)

passMethod('Hi', str.lower)

Alternately, we could use a string as the name of the method to look up on the passed-in object. That looks like:

def passMethod(obj, method):
    return getattr(obj, method)()

passMethod('Hi', 'lower')

Problem

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

Original source

Related problems