Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate a dictionary of methods of a class instance

I have a requirement where i want to map the class’s stringified method names to methods with their instance. Right now i am doing it manually. And i am needing this at many more places. What i want is a function with one parameter as a class instance which generates me this dictionary when i run the script.

class MyClass:
    def myFunc1(self,param1):
        pass
    def myFunc2(self,param2):
        pass

mycls = MyClass()

# a method that generates me a dict of method names as stringified method names and methods with instance as values
my_class_method_dict = my_method_generator(mycls)

print(my_class_method_dict)
# prints -> {'myFunc1':mycls.myFunc1,'myFunc2':mycls.myFunc2}
# this dict is hard coded right now 


I need it like this because i need to call these instance methods doing something like this
x = my_class_method_dict['myFunc1']()

what i have tried:

def my_method_generator(cls):
    return {str(method):method for method in dir(cls) if not method.startswith("__")}

# this returns {'myFunc1':mycls.myFunc1,'myFunc2':mycls.myFunc2}

and when i try this (i know obviously wrong):
def my_method_generator(cls):
    return {str(method):cls.method for method in dir(cls) if not method.startswith("__")}
# this returns AttributeError: 'cls' object has no attribute 'method'


I tried to look for a solution but not getting any. Please help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This should work. The reason is dir() returns a list of strings of the methods, not the actual method objects, so one way to fix this is using the getattr given the class and the method name to get the method object.

def my_method_generator(cls):
    return {method: getattr(cls, method) for method in dir(cls) if not method.startswith("__")}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading