-2

I have a class where I want to call different modules form it, depending on an input from the user.

In my mind it would look something like this:

class Test:
   def test1:
       print("Hello world")

   def test2:
       print("farewell world")

user = input("> ")
Test.f{user}

Where it now will call what the user has told it to, but it doesn't work. So my question is if it's possible, if it is then how I would accomplish it.

When trying examples from the given link, I keep encountering a problem for example where it tells me "TypeError: test1() takes 0 positional arguments but 1 was given"

when the input looks like so:

getattr(globals()['Test'](), 'test')()

this is not the only one, and all I have tried leads to problems. leading me to believe that either my problem is different, or I'm implementing it wrong.

Help with either scenario is much a appreciate.

TheVoidBeing
  • 11
  • 1
  • 4
  • 2
    Does this answer your question? [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) – Ken Y-N Jan 24 '20 at 08:18
  • Sadly, I could not get them to work for my problem. But thank you for the help. – TheVoidBeing Jan 24 '20 at 08:32
  • @TheVoidBeing please update your question with what you've tried from that link - as the question stands it's a duplicate. – CDJB Jan 24 '20 at 08:34

1 Answers1

0

You should try using getattr(). for example:

class Test:
    def test1():
        print("Hello world")

    def test2():
        print("farewell world")


userinput = input('Which function do you wish to call?\n')
# getattr() takes 2 parameters, class name, and attribute name.
myfunc = getattr(Test, userinput)
myfunc()

Csmeau4
  • 30
  • 6
  • 1
    I don't know why this worked, when something simulere in the other answer's didn't. But this has solved my problem. – TheVoidBeing Jan 24 '20 at 08:50