Brian M. Hunt
Brian M. Hunt

Reputation: 83770

Call a method of an object with arguments in Python

I want to be able to call different methods on a Python class with dynamic function name, e.g.

class Obj(object):
    def A(self, x):
        print "A %s" % x

    def B(self, x):
        print "B %s" % x

o = Obj()

 # normal route
o.A(1) # A 1
o.B(1) # B 1

 # dynamically
foo(o, "A", 1) # A 1; equiv. to o.A(1)
foo(o, "B", 1) # B 1

What is "foo"? (or is there some other approach?) I'm sure it must exist, but I just can't seem to find it or remember what it is called. I've looked at getattr, apply, and others in the list of built-in functions. It's such a simple reference question, but alas, here I am!

Thanks for reading!

Upvotes: 19

Views: 26979

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798356

Methods in Python are first-class objects.

getattr(o, 'A')(1)

Upvotes: 9

Sven Marnach
Sven Marnach

Reputation: 601291

Well, getattr indeed seems to be what you want:

getattr(o, "A")(1)

is equivalent to

o.A(1)

Upvotes: 46

Related Questions