Calling an object method with arguments in Python

I want to be able to call different methods in a Python class with a 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 oA(1) # A 1 oB(1) # B 1 # dynamically foo(o, "A", 1) # A 1; equiv. to oA(1) foo(o, "B", 1) # B 1 

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

Thanks for reading!

+8
python reflection methods
source share
2 answers

Well, getattr really seems like you want:

 getattr(o, "A")(1) 

equivalently

 oA(1) 
+30
source share

Methods in Python are first class objects.

 getattr(o, 'A')(1) 
+5
source share

All Articles