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
  • 101,766
  • 154
  • 423
  • 727

3 Answers3

5

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

BrenBarn
  • 228,001
  • 34
  • 392
  • 371
3

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

getattr(instance,method)()
MikeTGW
  • 385
  • 1
  • 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
  • 92,520
  • 20
  • 182
  • 218