map and self

Warren Focke wfocke at phoenixdsl.com
Fri Sep 15 14:37:40 EDT 2000


Larry Whitley:

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

This doesn't work because scopes don't nest in python - there's only
local and global.  self is local to myprint, and thus not visible in the
body of the lambda.

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

This does work because cntList is global, and thus visible, well,
globally, including in the body of the lambda.

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

A common idiom is to pass values in as default arguments:

class B:
    def myprint(self):
        print map( lambda x, self=self: self.cntList[x].cnt, ...


Warren Focke

-- 
Just because romance and rapture have so often served as a pretext for
curdled banality doesn't make the sentiments themselves obsolete.
 -- Michelle Goldberg



More information about the Python-list mailing list