Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 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 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...