Pass method to function using method name from string variable

TurtleMenistan :

I have a class with a constructor, two other methods, and a member list with the names of the two methods.

class Foo():
    def __init__(self):
        self.methods = ["self.foo", "self.bar"]
    def foo(self):
        print("foo")
        return 0
    def bar(self):
        print("bar")
        return 0

I have a function that takes a function as an argument, like this.

myFunction(func)

The function has global scope and would be used like this.

myFunction(self.foo)

I want to iterate through the items in the self.methods list and make a call to the function for each method name, but, as expected, a string is passed rather than the method itself. How do I pass the method like the above example, so like self.foo not "self.foo"?

Ch3steR :

From what I understand you can try this.

class Foo():
    def __init__(self):
        self.method=['foo','bar']
    def foo(self):
        print('foo')
    def bar(self):
        print('bar')
    def run_all(self):
        for m in self.method:
            getattr(self,m)()

a=Foo()
a.run_all() # iterating through self.method and executing them
# foo
# bar

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33243&siteId=1