Is there a way to loop through and execute all of the functions in a Python class?

后端 未结 6 1561
南方客
南方客 2020-12-09 06:30

I have

class Foo():
    function bar():
        pass

    function foobar():
        pass

Rather than executing each function one by one as

6条回答
  •  心在旅途
    2020-12-09 06:34

    This works and preserves the order:

    class F:
    
        def f1(self, a):
            return (a * 1)
    
        def f2(self, a):
            return (a * 2)
    
        def f3(self, a):
            return (a * 3)
    
        allFuncs = [f1, f2, f3]
    
    def main():
        myF = F()
        a = 10
        for f in myF.allFuncs:
            print('{0}--> {1}'.format(a, f(myF, a)))
    

    The output would be:

    10--> 10
    10--> 20
    10--> 30
    

    Note: The advantage of using this instead of F.__dict__.values() is that here you can have a list of those functions that you prefer to be called, and not necessarily all of them.

提交回复
热议问题