1

Note: A similar question already exists, albeit being for C#.

Let's suppose my code looks like the following:

class SomeClass:

    def __init__(self):
         pass

    def do(self):
        print("a")

class SomeOtherClass:

    def __init__(self):
         pass

    def do(self):
        print("b")

class B:

    def __init__(self):
         self.SomeClass = SomeClass()  
         self.SomeOtherClass = SomeOtherClass()

def __main__():
    myclass = B()
    desired_class = str(input("The method of which class do you want to execute? "))
    myclass.desired_class.do() 

I will not know at built-time what method of SomeClass will be called. If-then-else is also not very neat if you have 200 methods and no just 2 to choose from.

How is this done most efficiently in python?

Note: The method will always be an existing method of SomeClass.

Narusan
  • 482
  • 1
  • 5
  • 18
  • @MadPhysicist I actually haven't found this question, although I've been searching quite a lot. Thanks for pointing it out, this is obviously a duplicate as the answers are the same/similar. – Narusan May 26 '17 at 15:00
  • 1
    You can always opt to close your own question. It's a matter of finding the right search terms, which means knowing the right terminology, which is sort of a catch-22. You gotta start somewhere. – Mad Physicist May 26 '17 at 15:05
  • Is there a close button underneath, next to "edit"? – Mad Physicist May 26 '17 at 15:10
  • 1
    That's probably it. I guess you'll have to wait for others to close it. Did a button pop up asking you if the dupe answers your question? If so, clicking on it should close. – Mad Physicist May 26 '17 at 15:12
  • You can't have a variable called `class `; it's a reserved word. – pat May 26 '17 at 15:34
  • @pat Thanks for pointing it out. It was just an example and I didn't bother about proper names. I'll update the example though. – Narusan May 26 '17 at 15:36

1 Answers1

5

How about getattr?

class SomeClass:
    def bark(self):
        print("woof")

myclass = SomeClass()
method = input("What do you want to execute? ")
getattr(myclass, method)()

Result:

C:\Users\Kevin\Desktop>py -3 test.py
What do you want to execute? bark
woof
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • What about the updated problem? Will this work as well? – Narusan May 26 '17 at 14:59
  • 1
    Certainly. You only need to do `s = input("The method of which class do you want to execute? "); getattr(myclass, s).do()`. Then, when the user enters "SomeClass", it will execute myclass.SomeClass.do(). Note that you can't use "class" as a variable name because it is a reserved word. – Kevin May 26 '17 at 15:08