Ask for help about class variable scope (Re: Why doesn't a dictionary work in classes?)
Terry Reedy
tjreedy at udel.edu
Thu Dec 27 05:43:59 EST 2018
On 12/26/2018 9:53 PM, jfong at ms4.hinet.net wrote:
> I saw the code below at stackoverflow. I have a little idea about the scope of a class, and list comprehension and generator expressions, but still can't figure out why Z4 works and Z5 not. Can someone explain it? (in a not-too-complicated way:-)
>
> class Foo():
> XS = [15, 15, 15, 15]
> Z4 = sum(val for val in XS)
The iterable passed in to the comprehension is XS.
> try:
> Z5 = sum(XS[i] for i in range(len(XS)))
The iterable passed in to the comprehension function is range(len(XS)).
XS is a class name, not a global or outer function local name, hence
invisible to the inner function.
> except NameError:
> Z5 = None
>
> print(Foo.Z4, Foo.Z5)
>>>> 60 None
>
>
> --Jach
>
--
Terry Jan Reedy
More information about the Python-list
mailing list