map and self

Mike Fletcher mfletch at tpresence.com
Fri Sep 15 14:26:15 EDT 2000


This is actually a FAQ/language-wart, lambda statements in Python don't have
lexical scope (nothing does), so your lambda has access to its own local
variables and to the global variables of the module, but not to the
enclosing method's variables.  The standard hack around it is:

lambda x, self=self: self.whatever

That hackiness is part of the reason for introducing list comprehensions
with Python 2.0 (lexical scope not being liked by many old-school
Pythonistas, and thus not being a good solution in many minds).

[ self.cntList[x].cnt for x in range(len(self.cntList)) ]

or (more Pythonically)

[ object.cnt for object in self.cntList ]

Of course, in this particular example:

map( getattr, self.cntList, ["cnt"]*len(self.cntList) )

Should work even in version 1.5.2

HTH,
Mike

-----Original Message-----
From: Larry Whitley [mailto:ldw at us.ibm.com]
Sent: Friday, September 15, 2000 2:04 PM
To: python-list at python.org
Subject: map and self


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

class A:
    def __init__(self):
        self.cnt = 0

class B:
    def __init__(self):
        self.cntList = []
        for i in range(5):
            self.cntList.append( A() )
    def myprint(self):
        print map( lambda x: self.cntList[x].cnt, range(len(self.cntList)))

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

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

>>> cntList = []
>>> for i in range( 5 ):
>>>     cntList.append( A() )
>>> len(cntList)
5
>>> map( lambda x: cntList[x].cnt, range( len( cntList )))
[0, 0, 0, 0, 0]

So, my question... How do I get around the NameError: self problem and use
this sort of thing in methods internal to a class?

Larry


-- 
http://www.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list