I have following code, that doesn't work:
class Node:
n = 5
options = [ i / (n-1) for i in range(n)]
print("Success")
Error I am getting is:
Traceback (most recent call last):
File "/Users/ikkamens/Library/Preferences/PyCharm2019.2/scratches/counters.py", line 1, in <module>
class Node:
File "/Users/ikkamens/Library/Preferences/PyCharm2019.2/scratches/counters.py", line 3, in Node
options = [ i / (n-1) for i in range(n)]
File "/Users/ikkamens/Library/Preferences/PyCharm2019.2/scratches/counters.py", line 3, in <listcomp>
options = [ i / (n-1) for i in range(n)]
NameError: name 'n' is not defined
However, the following changed version works:
class Node:
n = 5
options = [ i / 4 for i in range(n)]
print("Success")
Why can I use the class level variable in range
expression, but not in (n-1)
? Is this an interpreter bug or is there some rule to explain this behavior? I have tried it with 3.8 and 3.6 interpreters.