Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method by annotation [duplicate]

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?

like image 932
User Avatar asked Dec 12 '25 04:12

User


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():...
like image 119
XxJames07- Avatar answered Dec 13 '25 23:12

XxJames07-