Question about map() and class methods

Preston Landers prestonlanders at my-deja.com
Mon Dec 20 17:07:51 EST 1999


Hey scott,

I'm not sure what you're ultimately trying to accomplish here, but a
couple of tips:

All class methods are called with *at least* one parameter, the class
instance (people use the word 'self' merely as a convention).  The map()
function will call its first parameter as a function once for each thing
in its second parameter (hopefully a list).  That function call will
have that thing as the only parameter (not including the implied class
instance parameter.)  Hope that made sense.

Your foo.bar() function only accepts one parameter, its class instance.
It needs to be something like:

class foo:
    def bar(self, thing):
        return thing + thing

In addition, I think you will need to instantiate your foo class before
you can use its methods, but I could be wrong.

So, you would do something like:

>>> foo_instance = foo()

>>> map(foo_instance.bar, [1, 2, 3])
[2, 4, 6]

You may find it helpful to reread the section on classes in the
tutorial.  Then again, you might not.

http://www.python.org/doc/current/tut/node11.html

cheers,

---Preston

In article <83lgi0$t$1 at nnrp1.deja.com>,
  malraux at my-deja.com wrote:
> Hi all,
>
> I was attempting to use a class method with map() the other day, and
> failed miserably.
>
> Basically, if I have a class foo:
>
> class foo:
>     def bar(self):
>         return(whatever)
>
> and I try to do this:
>
> x = map(foo.bar, someListOfFoos)
>
> The interpreter complains that foo.bar requires a class as its
> argument.  Obviously, if it would only continue with the call, it
would
> discover that yes, indeed, it has a whole list of them to chew on.
>
> I got around the problem by doing this:
>
> def mapFooBar(self):
>     foo.bar(self)
>
> map(mapFooBar, someListOfFoos)
>
> Which of course works fine.
>
> What am I missing here?
>
> Thanks,
>
> -scott
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list