wondering if there's any way to run a certain function based off the arguments we give an object. For example, if we pass 1, it will run function_1, but if we pass 2 it will run function_2. Like so:
class my_Class:
def func(self, num):
self.__dict__[f"func_{num}"](num)
def func_1(self, num):
print("test", num)
def func_2(self, num):
print("test", num)
class_obj = my_Class()
class_obj.func(1)
class_obj.func(2)
The output I'd want here is:
test 1
test 2
CodePudding user response:
Here is a solution you can try, using getattr
class my_Class:
def func(self, num):
self.__dict__[f"func_{num}"](num)
def func_1(self, num):
print("test", num)
def func_2(self, num):
print("test", num)
def run(self, func_id): # <-- wrapper that call's the inner function based on id
getattr(self, f"func_{func_id}")(func_id)
class_obj = my_Class()
class_obj.run(1) # <-- Call wrapper instead with function idx
class_obj.run(2)
CodePudding user response:
with an if or switch case
e.g.
class my_Class:
def func(self, num):
if(num == 1):
self.func_1(num)
if(num == 2):
self.func_2(num)
def func_1(self, num):
print("test", num)
def func_2(self, num):
print("test", num)
class_obj = my_Class()
class_obj.func(1)
class_obj.func(2)
CodePudding user response:
Code
class my_Class:
def func(self, num):
getattr(self,"func_" str(num))(num)
def func_1(self, num):
print("test", num)
def func_2(self, num):
print("test", num)
class_obj = my_Class()
class_obj.func(1)
class_obj.func(2)
Output:
test 1
test 2
Explination
You can use the function, getattr()
to call a function from a string, you can later on change that string to any format you want to be the source (dictionary, list, etc)
CodePudding user response:
You can achieve this by creating a map using list/tuple/dictionary that points to the functions, something like:
class MyClass: # search pep8 to see the conventional way of writing class names in python
def __init__(self):
self.functions_map = (self.func_1, self.func_2)
def func(self, functions_index, *args):
self.functions_map[functions_index](*args)
def func_1(self, num):
print("test", num)
def func_2(self, num):
print("test", num)
And then, in order to call the functions do something like:
class_obj = MyClass()
class_obj.func(0, 3) # remember indexes start at 0, and not 1
class_obj.func(1, 5)
Where 3 and 5 are the numbers being passed to func_1 and func_2 as arguments