Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 703
Brian M. Hunt Avatar asked Mar 30 '11 15:03

Brian M. Hunt


1 Answers

Well, getattr indeed seems to be what you want:

getattr(o, "A")(1)

is equivalent to

o.A(1)
like image 149
Sven Marnach Avatar answered Oct 01 '22 05:10

Sven Marnach