map and self
Larry Whitley
ldw at us.ibm.com
Fri Sep 15 14:10:35 EDT 2000
Never mind. I figured out that I am supposed to be saying:
class B:
def __init__(self):
self.cntList = []
for i in range(5):
self.cntList.append( A() )
def myprint(self):
print map( lambda x,y=self: y.cntList[x].cnt,
range(len(self.cntList)))
Right?
Larry
"Larry Whitley" <ldw at us.ibm.com> wrote in message
news:8ptoa6$12vi$1 at news.rchland.ibm.com...
> 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
>
>
More information about the Python-list
mailing list