Access the methods of a class

Bengt Richter bokr at oz.net
Fri Oct 31 12:31:24 EST 2003


On Fri, 31 Oct 2003 17:10:21 +0100, Fernando Rodriguez <frr at easyjob.net> 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.

I don't know off hand how to get the parameter count for built in methods, but:

 >>> class A(object):
 ...    def m_a1(self):pass
 ...    def m_a2(self, two):pass
 ...    def m_a3(self, two, three=3):pass
 ...
 >>> class Foo(A, list):
 ...     def m1(self): print 'm1'
 ...     def m2(self): print 'm2'
 ...     notamethod = 'not a method'
 ...     def sanity(self):
 ...         for name in dir(type(self)):
 ...             if not name.startswith('_'):
 ...                 x = getattr(self, name)
 ...                 if callable(x):
 ...                     nargs = hasattr(x,'func_code') and x.func_code.co_argcount or '??'
 ...                     print '%s has %s parameter%s' % (name, nargs, 's'[:nargs!=1] )
 ...     def twoarg(self, two): pass
 ...     def threearg(self, two, three): pass
 ...
 >>> foo = Foo()
 >>> foo.sanity()
 append has ?? parameters
 count has ?? parameters
 extend has ?? parameters
 index has ?? parameters
 insert has ?? parameters
 m1 has 1 parameter
 m2 has 1 parameter
 m_a1 has 1 parameter
 m_a2 has 2 parameters
 m_a3 has 3 parameters
 pop has ?? parameters
 remove has ?? parameters
 reverse has ?? parameters
 sanity has 1 parameter
 sort has ?? parameters
 threearg has 3 parameters
 twoarg has 2 parameters

Regards,
Bengt Richter




More information about the Python-list mailing list