0

Why the class attr cannot be used in this way?

class A:
    a = 1
    d = [1, 2, 3, 4]
    e = [i for i in d if i == a]
    print(e)

and the error message is like this below:

Traceback (most recent call last):
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 3, in <module>
    class A:
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 7, in A
    e = [i for i in d if i == a]
  File "/home/gavinc/code/eigen_clients/gavinc/a002.py", line 7, in <listcomp>
    e = [i for i in d if i == a]
NameError: name 'a' is not defined

there will be no error if I write this out side of a class, something like the following code:

a1 = 1
d1 = [1, 2, 3, 4]
e1 = [i for i in d1 if i == a1]
print(e1)
wim
  • 338,267
  • 99
  • 616
  • 750

1 Answers1

1

When it comes to classes, instance variables are defined inside an init method as below:

class A:
    def __init__(self):
        self.a = 1
        self.d = [1, 2, 3, 4]
        self.e = [i for i in self.d if i == self.a]
        print(self.e)

# Creating an object of the class in order to trigger __init__
A()

If you define variables directly inside the class, they'd be class variables. These can either be accessed through class instances (like instance variables usually are), or directly from the class name (like A.a, in your case).

Based on my tests, your code may be failing because the scope of the list comprehension does not contain a. I am not sure if this is because the class A still being constructed and hence lacks a proper scope to pass. I say this because replacing the comprehension with a for loop is yielding your expected results:

class A:
    a = 1
    d = [1, 2, 3, 4]
    e = []
    for i in d:
        if i == a:
            e.append(i)
    print(e)
    # [1]
shriakhilc
  • 2,922
  • 2
  • 12
  • 17