Call method from string [duplicate]
Asked Answered
A

4

55

If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it:

class CallMe: # Class

   def App(): # Method one

      ...

   def Foo(): # Method two

      ...

variable = "App" # Method to call

CallMe.variable() # Calling App()

But it couldn't. Any other way to do this?

Albumen answered 6/12, 2009 at 14:41 Comment(2)
How do you decide what value to place in variable?Willson
I would use an argument passed to the file. :)Albumen
D
129

You can do this:

getattr(CallMe, variable)()

getattr is a builtin method, it returns the value of the named attributed of object. The value in this case is a method object that you can call with ()

Depression answered 6/12, 2009 at 14:46 Comment(2)
Could you please tell me what do I do if I have a string whose value is "CallMe"?Wombat
The same approach works on the module. If CallMe was in a module imported as m, then getattr(m, 'CallMe') would return the class.Tartaric
P
3

You can use getattr, or you can assign bound or unbound methods to the variable. Bound methods are tied to a particular instance of the class, and unbound methods are tied to the class, so you have to pass an instance in as the first parameter.

e.g.

class CallMe:
    def App(self):
        print "this is App"

    def Foo(self):
        print "I'm Foo"

obj = CallMe()

# bound method:
var = obj.App
var()         # prints "this is App"

# unbound method:
var = CallMe.Foo
var(obj)      # prints "I'm Foo"
Provinciality answered 6/12, 2009 at 16:8 Comment(0)
L
1

Your class has been declared as an "old-style class". I recommend you make all your classes be "new-style classes".

The difference between the old and the new is that new-style classes can use inheritance, which you might not need right away. But it's a good habit to get into.

Here is all you have to do to make a new-style class: you use the Python syntax to say that it inherits from "object". You do that by putting parentheses after the class name and putting the name object inside the parentheses. Like so:

class CallMe(object): # Class

   def App(): # Method one

      ...

   def Foo(): # Method two

      ...

As I said, you might not need to use inheritance right away, but this is a good habit to get into. There are several questions here on StackOverflow to the effect of "I'm trying to do X and it doesn't work" and it turns out the person had coded an old-style class.

Langmuir answered 6/12, 2009 at 19:33 Comment(0)
S
0

Your code does not look like python, may be you want to do like this?

class CallMe:

    def App(self): #// Method one
        print "hello"

    def Foo(self): #// Method two
        return None

    variable = App #// Method to call

CallMe().variable() #// Calling App()
Schluter answered 6/12, 2009 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.