from my research, I understand that using getattr()
allows one to get a method on a certain object such as:
getattr(obj, method)
is the equivalent to
obj.method()
However, I tried to use it in my code and the statement returns a memory location:
<bound method _Class.method of <Class instance at 0x7f412df0c320>>
I don't understand what I am doing wrong. Any help is appreciated.
Methods are just attributes, and getattr()
retrieves attributes. As such
getattr(obj, 'method')
is the same as
obj.method
so without the ()
call primary, so no call to the method object made. Just add a call expression, to call the result of the getattr()
method:
getattr(obj, 'method')()
__getattr__
is a hook method to allow a class to customise how missing attributes are handled. You should generally not need to call it directly.