phillipstack phillipstack - 7 months ago 59
Python Question

Loop through object functions

returns a list of object attributes and functions. How can I iterate over all callable functions and get the output of the functions? (ASSUMING NO FUNCTION ARGS)

for a in dir(obj) if not a.startswith('__') and callable(getattr(obj,a)):
response = obj.a()

This does not work as python is treating a as the attribute name. Is there any way to do this?


you need to use getattr to actually get the callable and then call it ...

do this

fn = getattr(obj,a)

not this


of coarse you are not checking if the callable has any required arguments or anything like that ... im not sure what you are actually trying to accomplish... but im skeptical that this is the right technique

additionally you need one more ) on this line callable(getattr(obj,a):