Listed Class Variable Area

consider the following code fragment:

class a:
    s = 'python'
    b = ['p', 'y']
    c = [x for x in s]

conclusion:

>>> a.c
['p', 'y', 't', 'h', 'o', 'n']

but when I try to restrict the list if:

class a:
    s = 'python'
    b = ['p', 'y']
    c = [x for x in s if x in b]

Shows the following exception:

Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    class a:
  File "<pyshell#22>", line 4, in a
    c = [x for x in s if x in b]
  File "<pyshell#22>", line 4, in <listcomp>
    c = [x for x in s if x in b]
NameError: global name 'b' is not defined

If make global bworks, why is this happening?

+4
source share
1 answer

It's not so much about the scope of variables in list comprehension, but about how classes work. In Python 3 ( but not in Python 2! ), List contexts do not affect the area around them:

>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>> i = 0
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> i
0

, , b , . , , @property:

>>> class a:
...   s = 'python'
...   b = 'py'
...   @property
...   def c(self):
...     return [x for x in self.s if x in self.b]
... 
>>> A = a()
>>> A.c
['p', 'y']

, , ( ), b .

+6

Source: https://habr.com/ru/post/1534540/


All Articles