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!
Well, getattr
indeed seems to be what you want:
getattr(o, "A")(1)
is equivalent to
o.A(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With