0

I have many different methods in a class. Each method contains a function for a unique case. The case is passed to the constructor as a simple integer that identifies which method should be used. Is there a better way to set call this function then just a bunch of if statements?

class Class:
    def __init__(self, case):
        self.__case = case # case is a integer from 1 to 10
        if case == 1:
            self.case1()
        elif case == 2:
            self.case2()
        elif case == 3:
            self.case3() 
        ...
        elif case == 10:
            self.case10():

    def case1(self):
        ...
    def case2(self):
        ...
    def case10(self):

The code works but it is very redundant. Is there a more pythonic way of doing this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
thisissparzo
  • 37
  • 1
  • 8
  • 1
    Possible duplicate of [Replacements for switch statement in Python?](http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) – Sneftel Apr 22 '17 at 16:44

1 Answers1

2

Yes, there are better ways.

If your method names do not follow a pattern but there is a fixed number of them, use a list, then use case as an index:

cases = [None, self.case1, self.case2, ..., self.case10]
cases[case]()

You can build this list up-front with a decorator, but then you'd have to make sure you bind the function objects to self first:

class Class:
    def __init__(self, case):
        self._cases[case].__get__(self)()

    def case1(self):
        ...
    def case2(self):
        ...
    def case10(self):
        ...

    _cases = [case1, case2, ..., case10]

If your methods really are sequentially numbered, you can generate the method name and use getattr() to look up the method:

getattr(self, 'case{}'.format(case))()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343