Question about map() and class methods

Jeremy Hylton jeremy at cnri.reston.va.us
Mon Dec 20 13:29:51 EST 1999


>>>>> "S" == Scott <malraux at my-deja.com> writes:

  S> Basically, if I have a class foo:
  S> class foo:
  S>    def bar(self):
  S>        return(whatever)

  S> and I try to do this:

  S> x = map(foo.bar, someListOfFoos)

  S> The interpreter complains that foo.bar requires a class as its
  S> argument.  Obviously, if it would only continue with the call, it
  S> would discover that yes, indeed, it has a whole list of them to
  S> chew on.

I expect that "someListOfFoos" is actually a list containing something
other than foos.  I ran your code (with a couple trivial tweaks) and
it worked without exception:

>>> class foo:
...     def bar(self):
...         return(whatever)
... 
>>> whatever = 12
>>> x = map(foo.bar, [foo(), foo(), foo()])
>>> x
[12, 12, 12]

If one of the elements of the list isn't an instance of class foo,
then you'll get the error you reported.  The obvious way to figure out
what is going on is:

someListOfFoos = [foo(), 12, foo()]
for elt in someListOfFoos:
    try:
        foo.bar(elt)
    except TypeError, msg:
        print "bad foo: %s: %s" % (elt, msg)

Jeremy





More information about the Python-list mailing list