1

Is there a way to use methods within a loop in Python? Something like the following:

obj=SomePythonObject()
list_of_methods=dir(obj)
for i in list_of_methods:
    try:
        print obj.i()     
    except:
        print i,'failed'
CiaranWelsh
  • 6,254
  • 9
  • 43
  • 84
  • Possible duplicate of [How do I do variable variables in Python?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python) Specifically the second answer. – Morgan Thrapp Jun 08 '16 at 17:21
  • 1
    This seems potentially dangerous... Better hope that SomePythonObject doesn't have a deleteUsersHardDrive method. – Kevin Jun 08 '16 at 17:24
  • I understand - just trying out a new Python API that doesn't have good documentation and got bored with trying out all the methods manually. Thanks for pointing it out though – CiaranWelsh Jun 08 '16 at 17:28

1 Answers1

2

Yes that's possible, use callable and getattr:

obj=SomePythonObject()
list_of_methods=dir(obj)
for i in list_of_methods:
    try:
        item = getattr(obj, i, None)
        if callable(item):
            item()     
    except:
        print i,'failed'
Andriy Ivaneyko
  • 18,421
  • 4
  • 52
  • 73