Call method by annotation

Viewed 57

Given the code below

class Test:
  def method(self, name):
    if name == 'a':
      return __method_a()
    if name == 'b':
      return __method_b()

  def __method_a(self):
    print('a')

  def __method_b(self):
    print('b')
  ...

Is there a way to do something "nicer", for example by using annotations?

class Test:
  def method(self, name: str):
    return self.call_by_annot(name)

  @a
  def __method_a(self):
    print('a')

  @b
  def __method_b(self):
    print('b')
  ...

If not, which is an excellent way to remove such a list of if?

1 Answers

you could do something like this:

class Test:

    def method(self,name):
        return getattr(self,f"__method_{name}")()

    def __method_a():...
    def __method_b():...
Related