0

Have a look at this simple Python code:

class A:
    x = 123
    y = [(x,x*x) for x in [1,2,3]]

print A().x

A.x is 123, but when I do A().x, it prints 3. Why?

$ python a.py 
3
Dog
  • 7,707
  • 8
  • 40
  • 74

2 Answers2

1

It's a behaviour related to py2.x. In py2.x the list comprehensions don't have their own scope. So, the list comprehension in your case actually modified the variable x and as x was assigned the value 3 at the end of list comprehension so you'll get 3 for both A().x and A.x.

In py3.x this has been fixed:

...and in particular the loop control variables are no longer leaked into the surrounding scope.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • But there's no scope in class definitions? Why would there be one? The only reason I could think of is if you were allowed to do something like `class A: if True: z = 4`. – Dog Jul 27 '13 at 14:57
  • @Dog [Classes are namespaces themselves and yes they have scope.](http://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespaces) – Ashwini Chaudhary Jul 27 '13 at 15:01
0

You have overriden the x in the list comprehension. Should use another name.

zhangyangyu
  • 8,520
  • 2
  • 33
  • 43