-1
class A:
    def __init__(self):
        self.var = 10
    def print(self):
        print("hiiiiii")

For an object of A, we can easily access the attributes with getattr and setattr. Is there any way in Python to have an instance of class and a method name and call it indirectly, like:

MagicalMethod( A(), "print" )

then prints "hiiiiii" for me.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

That would be getattr:

>>> getattr(A(), 'print')()
hiiiiii

(Note that you still have to call the return value of getattr; you can define a wrapper to do that for you:

def MagicalMethod(obj, name, *args, **kwargs):
    return getattr(obj, name)(*args, **kwargs)

)

operator.methodcaller provides a slightly different kind of indirection.

>>> from operator import methodcaller
>>> f = methodcaller('print')
>>> f(A())
hiiiiii
chepner
  • 497,756
  • 71
  • 530
  • 681