What is the proper way to loop over a Python object's methods and call them?
Given the object:
class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
You can use the inspect module to get class (or instance) members:
>>> class C(object):
... a = 'blah'
... def b(self):
... pass
...
...
>>> c = C()
>>> inspect.getmembers(c, inspect.ismethod)
[('b', <bound method C.b of <__main__.C object at 0x100498250>>)]
getmembers() returns a list of tuples, where each tuple is (name, member). The second argument to getmembers() is the predicate, which filters the return list (in this case, returning only method objects)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With