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?
Just do getattr(instance, method)()
. getattr
returns the method object, which you can call with ()
like any other callable.
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.