0

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?

6
  • 1
    No, this wouldn't cause memory issues. But this design seems kind of silly -- why not just provide separate methods (with meaningful names!), and then let the caller use whichever method they want, instead of making them remember some obscure action type value? Commented Feb 19, 2023 at 15:54
  • The main purpose is to change the part of functionality of method(s) just by changing one property instead of putting multiple if blocks in a method. This is just an example, basicially a simplified version of a practical case, and the names are arbitrary. Commented Feb 19, 2023 at 16:00
  • 2
    Have you considered subclassing A? Commented Feb 19, 2023 at 16:11
  • 3
    This is a weird pattern. Using different subclasses would be the more standard solution. Another option could be defining a Protocol and having a factory function that returns the right function/object for the action type (which is practically speaking not very different from subclassing). Commented Feb 19, 2023 at 16:13
  • 1
    Again, subclassing is how I'd normally do this, because then it's less mysterious what version of the functionality you're getting (you can just look and see what type of object you have instead of having to do forensics to figure out how it was initialized). If it's just changing the functionality of part of the class, maybe the class should be refactored so that its functionality is more modular and you can swap out that part of it. If you think that's not workable, put together a demonstrative example. Commented Feb 19, 2023 at 16:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.