I need to have a python class to execute different actions depending on a certain parameter passed by the user upon creating an instance of the class.
To avoid using if blocks, I defined different versions of the method with different names.
class A:
def __init__(self, action_type):
self.action = object;
if action_type == 1:
self.action = self._action1;
elif action_type == 2:
self.action = self._action2;
else:
raise ValueError("Unknown action type")
def _action1(self):
print("Action1 is executed!");
def _action2(self):
print("Action2 is executed!")
The user call the action() method, which refers to either _action1() or _action2() based on action_type.
I know that this works, But is this a good practice to follow in python development? Could this cause memory issues?