Python: How can I check if an attribute of an object is a method or not?
attributes, object, python, types
Solution
You can use `inspect` for something like this:
from inspect import ismethod,getmembers
class Example:
def __repr__(self):
return "\n".join("%s: %s" % (k, v) for (k,v) in getmembers(self,lambda x: not ismethod(x)))
def method(self):
return 1
a = Example()
a.foo = 'bar'
print a
This also picks up the double underscore attributes (`__module__`, `__doc__`). If you don't want those, you can pretty easily filter them out.
Problem
I want to define a class with it's `__repr__` method defined in such a way that it will write out only the names and values of all attributes that are not methods. How can I do this? I have managed to write it like this, but I realize that this does not check for the attribute type. ``` class Example: def __repr__(self): return "\n".join(["%s: %s" % (x, getattr(self, x)) for x in dir(self) if not x.startswith('__')]) ``` What is missing here is the check for the type of the attribute.