4

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
User
  • 806
  • 1
  • 11
  • 28
  • 2
    Does [Call a Python method by name](https://stackoverflow.com/questions/3521715/call-a-python-method-by-name) answer your question? – wwii May 24 '22 at 13:37
  • 1
    .. [Calling a function of a module by using its name (a string)](https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string) – wwii May 24 '22 at 13:38
  • 1
    Maybe combine `getattr` with a class attribute mapping letters to method names (e.g.`{'a':'__method_a',...` – wwii May 24 '22 at 13:41

1 Answers1

1

you could do something like this:

class Test:

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

    def __method_a():...
    def __method_b():...
XxJames07-
  • 1,833
  • 1
  • 4
  • 17