Can ask a class for its functions?
Kevin Altis
altis at semi-retired.com
Thu Aug 15 11:50:30 EDT 2002
"Troy Melhase" <troy at gci.net> wrote in message
news:ulm3d0envo0mbe at corp.supernews.com...
> Or more list-comprehension-ly?
>
> [x for x in clazz.__dict__.values() if callable(x)]
This almost works except that it only gives you the methods defined in the
class, it doesn't include methods from any of the superclasses.
>>> class A:
... a = 'hello'
... def aMethod(self):
... print a
...
>>> [x for x in A.__dict__.values() if callable(x)]
[<function aMethod at 0x0156D8C0>]
>>> class B(A):
... b = 'world'
... def bMethod(self):
... print b
...
>>> [x for x in B.__dict__.values() if callable(x)]
[<function bMethod at 0x0156AD78>]
The first use of filter Peter provides below does appear to work correctly,
picking up superclass methods.
>>> filter(callable, [getattr(B, attr) for attr in dir(B)])
[<unbound method B.aMethod>, <unbound method B.bMethod>]
It looks like you can also use that on an instance of a class. I wonder
whether these results are Python 2.2.x specific? PythonCard has been using
an elaborate method to recurse over an instance variable using __bases__ and
it would be nice to replace that.
ka
>
> Peter Hansen wrote:
>
> > Troy Melhase wrote:
> >>
> >> This doesn't work because dir() returns a list of strings, none of
which
> >> are callable.
> >>
> >> What you meant was:
> >>
> >> filter(callable, [getattr(class_, attr) for attr in
dir(class_)])
> >
> > Or more simply?
> >
> > filter(callable, clazz.__dict__.values())
> >
> > -Peter
>
> --
> Troy Melhase
> mailto:troy at gci.net
> http://melhase.com/
>
More information about the Python-list
mailing list