An instance's method is nothing more than a function
object stored in the instace's __dict__
. This said, you are doing correct to find them, except that maybe, the class indeed has the attribute corresponding to your argument string, but is not a function, is just another type instead.
If you depend on this, I recommend you refactor the instance's function looking code into a helper method:
import types
def instance_has_method(instance, name):
try:
attr = getattr(instance, name)
return isinstance(attr, types.FunctionType)
except AttributeError:
return False
Once you have this function, your code will be more concise because now you're sure that the attribute is indeed a function and can be callable.
The code above checks if the attribute is a function. If you want something wider, you can check if it's a callable
like this: return hasattr(attr, '__call__')
.
In python, this is basically how you check for attributes inside classes. I don't think there's nothing wrong with your approach and not another more clever way to do reflection.
Hope this helps!