Ask for help about class variable scope (Re: Why doesn't a dictionary work in classes?)

jfong at jfong at
Wed Dec 26 21:53:25 EST 2018

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)
        Z5 = sum(XS[i] for i in range(len(XS)))
    except NameError:
        Z5 = None

print(Foo.Z4, Foo.Z5)
>>> 60 None


More information about the Python-list mailing list