0

How would I do the following:

instance.method()

I know I can do getattr(instance, method) to get instance.method, but is there a builtin to actually run that method?

David542
  • 104,438
  • 178
  • 489
  • 842

3 Answers3

5

Just do getattr(instance, method)(). getattr returns the method object, which you can call with () like any other callable.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
3

All you need to do is add a () to the end:

getattr(instance,method)()
MikeTGW
  • 395
  • 2
  • 10
1

You can use operator.methodcaller to create a function that will run that method on the passed instance when executed. However you still have to actually call it on an instance.

from operator import methodcaller

call_hello = methodcaller('hello', 'Jack')

call_hello(something)   # same as something.hello('Jack')

This is useful when you want to call the same method, for which you don't know the name, on different instances.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231