[solved] How to call all methods of a class ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[solved] How to call all methods of a class ?

I want to list all the methods using dir() and then want to excute it one by one which will return something.. here is my attempt but it's giving AttributeError: https://code.sololearn.com/c8A5lgmloeH5/?ref=app

17th Jul 2021, 6:58 PM
Ratnapal Shende
Ratnapal Shende - avatar
4 Answers
+ 7
Ratnapal Shende Your code always calls the method() method on 'test'. It doesn't matter if there is a variable named 'f', x.f() will always call x.f Calvin Thomas Use of eval() is discouraged. There is a cleaner way to get the methods and do it without try-catch, which is to use and getattr() to get the member using the member name, and then using callable() to check if the member is callable (is a method) https://code.sololearn.com/cN3QjixUe4TT/?ref=app
17th Jul 2021, 7:28 PM
XXX
XXX - avatar
+ 1
Ratnapal Shende You are doing it wrong, as you are calling an undefined method using the method variable. Here's the corrected code: for x in dir(test): try: # Is a method # Optional 'if x[0] != "_"' print(eval(f"test.{x}()")) except: # Is a property pass # Hope this helps
17th Jul 2021, 7:03 PM
Calvin Thomas
Calvin Thomas - avatar
+ 1
XXX Oh, thank you for the advice.
17th Jul 2021, 7:33 PM
Calvin Thomas
Calvin Thomas - avatar
0
Did something like that a long time ago. https://code.sololearn.com/ccVUSFXO3IZU/?ref=app
17th Jul 2021, 10:16 PM
Louis
Louis - avatar