Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

python - Variable Scope In Generators In Classes

I think that I know how variables and generators work in Python well.
However, the following code makes me confused.

from __future__ import print_function

class A(object):
    x = 4
    gen = (x for _ in range(3))

a = A()
print(list(a.gen))

When run the code (Python 2), it says:

Traceback (most recent call last):
  File "Untitled 8.py", line 10, in <module>
    print(list(a.gen))
  File "Untitled 8.py", line 6, in <genexpr>
    gen = (x for _ in range(3))
NameError: global name 'x' is not defined

In Python 3, it says NameError: name 'x' is not defined
but, when I run:

from __future__ import print_function

class A(object):
    x = 4
    lst = [x for _ in range(3)]

a = A()
print(a.lst)

The code doesn't work in Python 3, but it does in Python 2, or in a function like this

from __future__ import print_function

def func():
    x = 4
    gen = (x for _ in range(3))
    return gen

print(list(func()))

This code works well in Python 2 and Python 3 or on the module level

from __future__ import print_function

x = 4
gen = (x for _ in range(3))

print(list(gen))

The code works well in Python 2 and Python 3 too.

Why is it wrong in class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because x is a class attribute (static variable), which you access like,

Example

>>> class A(object):
...     x = 4
...     gen = (A.x for _ in range(3))
...
>>> a = A()
>>> list(a.gen)
[4, 4, 4]

Here even gen is another class attribute, which means that,

>>> b = A()
>>> list(b.gen)
[]

This gives empty because the generator has already exhausted.


This happens because the generator is evaluated only when you issue a.gen, when it won't be able to resolve the name x.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...