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'
3
  • Possible duplicate of How do I do variable variables in Python? Specifically the second answer. Commented Jun 8, 2016 at 17:21
  • 1
    This seems potentially dangerous... Better hope that SomePythonObject doesn't have a deleteUsersHardDrive method. Commented Jun 8, 2016 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 Commented Jun 8, 2016 at 17:28

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

"item = getattr(obj, im item)" im item?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.