19

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!

2 Answers 2

46

Well, getattr indeed seems to be what you want:

getattr(o, "A")(1)

is equivalent to

o.A(1)
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to do the same thing but from a class name instead of a method name ? E.g. getClass("MyClassName") and than use the getattr() method on this object to get a method inside it ?
@Tareck117: You can use globals()["MyClass"] to look up a name in the global scope of the current module, or getattr(some_module, "MyClass") if it's in a different module. That said, in most (~99%) of the cases I've seen people using class or variables names as data, they had an issue with their design.
Thanks @Sven, I guess this will help me but since you think I may have a design problem I'll explain myself (I'm coming from a ASP/C# perspective): I would like to call a Python Web Service (CheeryPy) via some $.ajax call in javascript by passing the name of the controller to execute and the name of the method to call in the controller to create some sort of router. Do you know a cleaner way of doing this ?
Also, is it a bad pratice to call a method from a string argument using the getattr(o, "A")(1) call ?
@Tareck117: It's hard to know without the context. There are valid uses for globals(), and there are valid uses for getattr(), but both are also abused often. My feeling is that most uses of globals() are questionable. Never use getattr() with a string literal as second argument -- use normal argument access in that case.
9

Methods in Python are first-class objects.

getattr(o, 'A')(1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.