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
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
+ 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
+ 1
XXX Oh, thank you for the advice.
0
Did something like that a long time ago.
https://code.sololearn.com/ccVUSFXO3IZU/?ref=app