[Tutor] Ask a class for it's methods

Andreas Kostyrka andreas at kostyrka.org
Sat Dec 13 02:59:34 CET 2008


On Fri, Dec 12, 2008 at 06:06:35PM -0500, Shrutarshi Basu wrote:
> I have a list containing strings like :
> 
> func1[]
> func2[1,2]
> func3[blah]
> 
> I want to turn them into method calls (with numeric or string
> arguments) on a supplied object. I'm trying to figure out the best way
> to do this. Since these lists could be very big, and the methods could
> be rather complex (mainly graphics manipulation) I would like to start
> by getting a list of the object's methods and make sure that all the
> strings are valid. Is there a way to ask an object for a list of it's
> methods (with argument requirements if possible)?

Well, there are ways, but they are not reliable by design. Objects can return dynamically
methods.

So use something like this:

if callable(getattr(obj, "func1")):
    # func1 exists.

Guess nowaday with Python3 released, you should not use callable, but instead
test on __call__

if hasattr(getattr(obj, "func1"), "__call__"):



> The next question is once I've validated the list, what's the easiest
> way to turn the list element into a method call? I'll be parsing the
> string to separate out the method name and arguments. If I store the
> method name (say func1)  in a variable, say var, could I do
> object.var() and have if call the func1 method in object?
getattr(object, var)() # calls the method named in var:

class A:
    def x(self, a, b):
        return a + b

instance = A()

name = "x"

args_positional = (1, 2)

print getattr(instance, name)(*args_positional) # prints 3

args_by_name = dict(a=1, b=2)

print getattr(instance, name)(**args_by_name) # prints 3 too.

Andreas


More information about the Tutor mailing list