I'm trying to get all the user-defined methods name from a class, ex:
class MyClass:
def __init__(self, param1, param2):
pass
def one_method(self):
pass
def __repr__(self):
pass
def __str__(self):
pass
def __my_method_no_2(self, param2):
pass
def _my_method_no_3(self):
pass
so far I have come to the following approach:
import inspect
[name for name, _ in inspect.getmembers(MyClass, inspect.isroutine)
if name not in {'__init_subclass__', '__subclasshook__'} and
getattr(MyClass, name).__qualname__.startswith(MyClass.__name__)]
output:
['_MyClass__my_method_no_2',
'__init__',
'__repr__',
'__str__',
'_my_method_no_3',
'one_method']
this is the expected output, but this looks "ugly" and not even sure if is the right approach
Got the idea from here, but using __dict__
instead of dir
.
Every python objects has a __dict__
attribute containing names of all attributes. Relevant docs here
The idea is: get a list of attributes from __dict__
and filter out everything non-callable
[attr for attr in MyClass.__dict__ if callable(getattr(MyClass, attr))]
Matches with your output
In Python 3.x
, you can use dir without inspect or any external libraries:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
To handle every method that you newly define in your class and override in your class, Try this:
class MyClass:
li = []
def __init__(self, param1, param2):
pass
def one_method(self):
pass
def __repr__(self):
pass
def __str__(self):
pass
def __my_method_no_2(self, param2):
pass
def _my_method_no_3(self):
pass
print([func for func in dir(MyClass) if callable(getattr(MyClass, func)) and func in MyClass.__dict__])
Outputs:
['_MyClass__my_method_no_2', '__init__', '__repr__', '__str__', '_my_method_no_3', 'one_method']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With