Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over a Python / IronPython Object Methods

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"
like image 962
BuddyJoe Avatar asked Dec 13 '22 04:12

BuddyJoe


1 Answers

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)

like image 137
dcrosta Avatar answered Dec 27 '22 09:12

dcrosta