0

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

7
  • 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. Commented Apr 11, 2020 at 18:27
  • 2
    Does this answer your question? How do I get list of methods in a Python class? Once you have the list of methods, you can just take its len(). Commented Apr 11, 2020 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 Commented Apr 11, 2020 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. Commented Apr 11, 2020 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 Commented Apr 11, 2020 at 21:02

2 Answers 2

2

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']
Sign up to request clarification or add additional context in comments.

Comments

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}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.