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,613
  • 3
  • 16
  • 26
  • 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
  • 103,130
  • 11
  • 146
  • 174
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
  • 113,587
  • 18
  • 171
  • 175