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.
Use the source
The first argument being
self
is just by convention. By accessing the method by name from the Class's dict, you are bypassing the binding, so it appears to be a function rather than a methodIf you want to access the method by name use
You could use dir to get the name of available methods/attributes/etc, then iterate through them to see which ones are methods. Like this:
I'm expecting there to be a cleaner solution, but this could be something you could use if nobody else comes up with one. I'd like if I didn't have to use an instance of the class to use getattribute.
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 ofMethodType
that 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
From a comment made on @THC4k's answer, it looks like the OP wants to discriminate between built-in methods and methods defined in pure Python code. User defined methods are of
types.MethodType
, but built-in methods are not.You can get the various types like so:
which prints:
Well, do you mean that
obj.mymethod
is a method (with implicitly passedself
) whileKlass.__dict__['mymethod']
is a function?Basically
Klass.__dict__['mymethod']
is the "raw" function, which can be turned to a method by something called descriptors. This means that every function on a class can be both a normal function and a method, depending on how you access them. This is how the class system works in Python and quite normal.If you want methods, you can't go though
__dict__
(which you never should anyways). To get all methods you should doinspect.getmembers(Klass_or_Instance, inspect.ismethod)
You can read the details here, the explanation about this is under "User-defined methods".