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

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

    No. You can access Foo.__dict__, and call each value in turn (catching errors for non-callable members), but the order is not preserved.

    for callable in Foo.__dict__.values():
        try:
            callable()    
        except TypeError:
            pass
    

    This assumes none of the functions take parameters, as in your example.

提交回复
热议问题