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.
>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("__")}