I’m trying to get the name of all methods in my class.
When testing how the inspect module works, i extraced one of my methods by obj = MyClass.__dict__['mymethodname'].
But now inspect.ismethod(obj) returns False while inspect.isfunction(obj) returns True, and i don’t understand why. Is there some strange way of marking methods as methods that i am not aware of? I thought it was just that it is defined in the class and takes self as its first argument.
You are seeing some effects of the behind-the-scenes machinery of Python.
When you write
f = MyClass.__dict__['mymethodname'], you get the raw implementation of “mymethodname”, which is a plain function. To call it, you need to pass in an additional parameter, class instance.When you write
f = MyClass.mymethodname(note the absence of parentheses after mymethodname), you get an unbound method of class MyClass, which is an instance ofMethodTypethat wraps the raw function you obtained above. To call it, you need to pass in an additional parameter, class instance.When you write
f = MyClass().mymethodname(note that i’ve created an object of class MyClass before taking its method), you get a bound method of an instance of class MyClass. You do not need to pass an additional class instance to it, since it’s already stored inside it.To get wrapped method (bound or unbound) by its name given as a string, use
getattr, as noted by gnibbler. For example:or