What is the proper way to loop over a Python object's methods and call them?
Given the object:
class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
What is the proper way to loop over a Python object's methods and call them?
Given the object:
class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
Edit
Daniel, you are wrong.
http://docs.python.org/reference/datamodel.html
Therefore, anything that defines __call__ and is attached to an object is a method.
Answer
The proper way to see what elements an object has is to use the dir() function.
Obviously this example only works for functions that take no arguments.
This code snippet will call anything it will find in
obj
and store results in mapping, where key is attribute name —dict((k, v()) for (k, v) in obj.__dict__.iteritems() if k.startswith('something'))
You can use the inspect module to get class (or instance) members:
getmembers() returns a list of tuples, where each tuple is (name, member). The second argument to getmembers() is the predicate, which filters the return list (in this case, returning only method objects)
Methods vs. functions and other types of callables...
(To address the issue in the comments in Unknown's post.)
First, it should be noted that, in addition to user-defined methods, there are built-in methods, and a built-in method is, as the doc at http://docs.python.org/reference/datamodel.html says, "really a different disguise of a built-in function" (which is a wrapper around a C function.)
As for user-defined methods, as Unknown's cited quote says:
But this does not mean that "anything that defines
__call__
and is attached to an object is a method." A method is a callable, but a callable is not necessarily a method. User-defined methods are wrappers around what the quote says.Hopefully this output (from Python 2.5.2 which I have handy) will show the distinction:
And - editing to add the following additional output, which is also relevant...
I wont add more output, but you could also make a class an attribute of another class or instance, and, even though classes are callable, you would not get a method. Methods are implemented using non-data descriptors, so look up descriptors if you want more info on how they work.