As Python can have multiple classes in one file/module, then how to read Number of Methods class by class?
2 Answers
The quick way is to simply run the built in dir() function on a class.
Any non-dunder method is typically meant to be used by the programmer.
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Comments
let's assume you have a module my_module.py:
class MyClass1:
def __init__(self, param1, param2):
pass
def one_method(self):
pass
class MyClass2:
def __init__(self):
pass
def one_method(self):
pass
def two_method(self):
pass
if you want the number of user-defined methods from each class you can use:
import inspect
import my_module
class_name_obj = inspect.getmembers(my_module, inspect.isclass)
{c: len([m for m in i.__dict__ if callable(getattr(i, m))]) for c, i in class_name_obj}
output:
{'MyClass1': 2, 'MyClass2': 3}
len().inspect.ismethodused to include unbound methods in Python 2 but now only does bound.inspect.isroutineshould work instead.inspect.isroutinewill give you both the user-defined methods and the built-in methods, I think the OP wants only the user-defined methods, even he didn't mention this