map and self

Piet van Oostrum piet at
Fri Sep 15 20:50:25 CEST 2000

>>>>> "Larry Whitley" <ldw at> (LW) writes:

LW> I'm having trouble understanding "self" when used within a map().
LW> Here's my problem:

self is in itself :=) nothing special. It is just an identifier like any
other. You could consistantly replace it with e.g donald_duck.

Your problem has also nothing to do with map. It would be the same with any
other function.

LW>     def myprint(self):
LW>         print map( lambda x: self.cntList[x].cnt, range(len(self.cntList)))

identifiers in a lambda must be either local (i.e. parameters of the
lambda), or global (defined in the module or builtin. Your use of self is
neither: it is a parameter of myprint. Python (unfortunately) doesn't have
intermediate scopes.

The usual solution is:

print map( lambda x, self=self: self.cntList[x].cnt, range(len(self.cntList)))

>>>> b = B()
>>>> b.cntList[1].cnt
LW> 0
>>>> b.myprint()
LW> Traceback (innermost last):
LW>   File "<interactive input>", line 1, in ?
LW>   File "<interactive input>", line 7, in myprint
LW>   File "<interactive input>", line 7, in <lambda>
LW> NameError: self

LW> Yet, when I perform the above actions interactively, it works as expected.
LW> (Note that I left "self" off here since it is inappropriate in outside the
LW> context of a class.)

No, it is not. self is as inappropriate as b.
Piet van Oostrum <piet at>
Private email: P.van.Oostrum at

More information about the Python-list mailing list