On Sun, Jun 23, 2013 at 10:38 PM, Jim Mooney <cybervigila...@gmail.com> wrote: > What about class variables instead of globals?, I put this in the my > lazy typer module, maker.py, which works fine to persist the numbers > between function calls so I can increment them: > > class count: > dict = list = set = tuple = 0 > > then I use count.dict += 1 , etc. > > Would that restrict python from an upward search, or am I dreaming?
A class body is compiled and evaluated as a function (with unoptimized locals), but this function isn't searched as a nested scope. Otherwise the methods of the class could refer to class attributes without using __getattribute__, which would be confusing as it would bypass descriptor binding (i.e. properties, bound methods). But a consequence of this rule also tends to frustrate people: >>> class Spam: ... n = 2 ... evens = [x for x in range(10) if x % n == 0] ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in Spam File "<stdin>", line 3, in <listcomp> NameError: global name 'n' is not defined In this case, the <listcomp> function is compiled to skip the class scope and instead use LOAD_GLOBAL to find n. Since the class name "Spam" isn't bound yet (the class object doesn't exist yet), you can't get around the problem by using Spam.n. Here's an example that shows the class scope getting skipped to instead use the outer scope of function f(): >>> def f(): ... n = 2 ... class Spam: ... n = 3 # skip this ... evens = [x for x in range(10) if x % n == 0] ... return Spam.evens ... >>> f() [0, 2, 4, 6, 8] > And yes, I got rid of the Basic-style names D1, D2. The program now > converts numbers to human-names up to dict_ninety_nine = , for > instance. And no, I didn't type ninety_nine dictionary entries to do > that. I'm too lazy a typer ;') Oh my. I don't think using the numbers spelled out makes it any better. I couldn't keep dict_thirty_four vs dict_sixty_five straight in my head to save my life. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor