1

I have a class that I want to call its methods using just strings. How do I do that?

class MyClass:
    def do_something():
        print 'MyClass did something'

MyClass.get_method('do_something')()
Timothy Clemans
  • 1,483
  • 3
  • 14
  • 25
  • You can also just hold the method object in a variable, in case that makes your life easier. – Marcin Sep 16 '13 at 22:28

2 Answers2

1
class MyClass:
    def do_something(self):
        print 'MyClass did something'

getattr(MyClass(),'do_something')()
Joran Beasley
  • 93,863
  • 11
  • 131
  • 160
1

You can do:

class MyClass:

    @staticmethod
    def do_something():
        print 'MyClass did something'

And call:

getattr(MyClass, 'do_something')()

Note the addition of @staticmethod to the method to ensure it can be called without a class instance.

Simeon Visser
  • 106,727
  • 18
  • 159
  • 164