Question about map() and class methods

dj trombley badzen at yifan.net
Mon Dec 20 12:15:19 EST 1999


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.


It seems you might want the following:

class foo:
   def bar(self):
   return(whatever)

x = map(<foo_instance>.bar, someListOfFoos)


Calling an unbound method always requires explicitly passing the first
argument; further unbound methods have a different type than instance
methods.  If you want a method to behave as a 'static method' might in
other OOP languages, you can of course declare it in the class without
the first argument, and always make the call unbound to any instance,
ie. with the class name.  But, for extra tweak value, consider the
following example of what I term 'argument promotion':

class foo:
   global b
   def bar(s, arg = None):
         if arg == None:
            print "Adding to the class-wide \"b\""
	    b = b + s 
         else:
            print "Adding to the instance's \"b\""
	    b = b + arg

Now, the function bar can be called as foo.bar(<single numeric
argument>) or <foo_instance>.bar(<single numeric argument>), and will
act differently according to if you want the 'static' version or the
'instance' version.  

Dave_the_Python_enthusiast:  Try _that_ in Java!
Dave_the_Java_enthusiast:  Yecch.  Why would I do a thing like that??

In any case, you can see that bound calling in Python is quite flexible.

On a more general note, the issue which I think is at the bottom of why
so many people initially encounter this sort of confusion is a syntactic
one:  that is, we often refer to what is best said as "the potential
concrete incarnations of the code block defined with name <bar> in the
scope of <foo>" simply as foo.bar, but that is a syntax collision with
the _unbound_method_ foo.bar; it would be nice if there was a convention
that humans could use to talk about the former when ambiguity arises. 
Anyone have any other thoughts on the issue?

-dj

Dave Trombley
<badzen at yifan.net>



More information about the Python-list mailing list