Access the methods of a class

Alex Martelli aleax at aleax.it
Fri Oct 31 12:22:48 EST 2003


Fernando Rodriguez wrote:

> Hi,
> 
> I have a base class with a 'sanity-check' method. This method should
> iterate through all the methods and check if they are all 'thunks' (zero
> parameter functions, well actually, 1 parameter: self).
> 
> How can I access the list of methods of a given object?  BTW, this class
> will be inherited from, so it should work with hte derived classes too.
> 
> How can I check the number of parameters of a given function object?
> 
> TIA O:-)
> 
> PS Any pointers to a python reflection tutorial, would also be
> appreciated.

Check out module inspect in the standard library.  It does the job
AND it's great example code for the actual lower-level mechanisms
Python offers for reflection.

>>> class base(object):
...   def a(self): pass
...   def b(self): pass
...   def c(self): pass
...
>>> class deriv(base):
...   def c(self): pass
...   def d(self): pass
...
>>> import inspect as i
>>> i.getmembers(deriv, i.ismethod)
[('a', <unbound method deriv.a>), ('b', <unbound method deriv.b>), ('c',
<unbound method deriv.c>), ('d', <unbound method deriv.d>)]
>>> for name, method in i.getmembers(deriv, i.ismethod):
...     print name, len(i.getargspec(method)[0])
...
a 1
b 1
c 1
d 1

there -- you have the methods and the number of arguments for each.

You can also easily do more refined checks, e.g. if a method takes
*args or **kwargs the [1] and [2] items of the tuple getargspec
returns about it are going to be non-None, and in the [3] item you
have a tuple of default values so you know how many of the [0] argument
names are optional...


Alex





More information about the Python-list mailing list