0

I have a maybe silly question. Let's take the example below.

class Myclass():

    def __init__(self):
        pass

    def function_1(self):
        print("1")

    def function_2(self):
        print("2")

variable = "1"

if variable == "1":
    Myclass().function_1()
if variable == "2":
    Myclass().function_2()

Would it be possible to replace the "if" conditions with something like:

Myclass().function_{0}().format(variable)

If yes, how ?

John
  • 89
  • 1
  • 8
  • `d = {"1": Myclass().function_1, "2":Myclass().function_2}` and `d["1"]()` ... but.... why? And thos would all be different Instances of Myclass ... – Patrick Artner Nov 20 '20 at 15:27
  • Because I have a lot of functions, and depending on one variable I need to call one or the other... So: just to avoid 200 if conditions. :) – John Nov 20 '20 at 15:28
  • `def DoIt(variable): if variable == "1": self.Do_1() elif ...` + `Myclass().DoIt("1")` with your classmethod kindof a facade for features ... but my guess would be thats a problem by design on your part to begin with :) – Patrick Artner Nov 20 '20 at 15:29
  • Thank you Patrick – John Nov 20 '20 at 16:36

1 Answers1

1

You could use getattr to dynamically get a method from its name:

getattr(Myclass(), 'function_{0}'.format(variable))()
Mureinik
  • 297,002
  • 52
  • 306
  • 350