0

As Python can have multiple classes in one file/module, then how to read Number of Methods class by class?

  • 1
    Are you initiating the classes at all? or are you trying to read from file? If you can be more specific about the manner you want to find the methods it can help get you the correct answer. – jgetner Apr 11 '20 at 18:27
  • 2
    Does this answer your question? [How do I get list of methods in a Python class?](https://stackoverflow.com/questions/1911281/how-do-i-get-list-of-methods-in-a-python-class) Once you have the list of methods, you can just take its `len()`. – wjandrea Apr 11 '20 at 18:40
  • @wjandrea the accepted answer from your suggested link it doesn't even work (at least not in python 3.7), and that question it doesn't address for user-defined methods, for which I think the OP may want – kederrac Apr 11 '20 at 20:52
  • @kederrac Looks like `inspect.ismethod` used to include unbound methods in Python 2 but now only does bound. `inspect.isroutine` should work instead. – wjandrea Apr 11 '20 at 21:00
  • `inspect.isroutine` will 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 – kederrac Apr 11 '20 at 21:02
  • @kederrac Then I think `inspect.isfunction` will work – wjandrea Apr 11 '20 at 21:03
  • if you have a bse_class, `inspect.isfunction` will give you also the base class and you do not want this – kederrac Apr 11 '20 at 21:05

2 Answers2

1

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']
Teejay Bruno
  • 1,716
  • 1
  • 4
  • 11
0

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}
kederrac
  • 16,819
  • 6
  • 32
  • 55