map and self
Piet van Oostrum
piet at cs.uu.nl
Fri Sep 15 20:50:25 CEST 2000
>>>>> "Larry Whitley" <ldw at us.ibm.com> (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
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
The usual solution is:
print map( lambda x, self=self: self.cntList[x].cnt, range(len(self.cntList)))
>>>> b = B()
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 cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl
More information about the Python-list