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

后端 未结 6 1554
南方客
南方客 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:35

    Since Python stores the methods (and other attributes) of a class in a dictionary, which is fundamentally unordered, this is impossible.

    If you don't care about order, use the class's __dict__:

    x = Foo()
    results = []
    for name, method in Foo.__dict__.iteritems():
        if callable(method):
            results.append(method(x))
    

    This also works if the function takes extra parameters - just put them after the instance of the class.

提交回复
热议问题