Unable to use list comprehension with class-variable function

69 Views Asked by At
class A:
    func = lambda x: x+4
    added_values = [func(45)]


if __name__=="__main__":
    print(A.added_values)

The above code outputs [49], that is expected. Then why this code

class A:
    func = lambda x: x+4
    added_values = [func(45) for _ in range(1)]


if __name__=="__main__":
    print(A.added_values)

gives undefined error, what is happening here?

Traceback (most recent call last):
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 1, in <module>
    class A:
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 3, in A
    added_values = [func(45) for _ in range(1)]
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 3, in <listcomp>
    added_values = [func(45) for _ in range(1)]
NameError: name 'func' is not defined

I do not know what is happening under the hood, looks very strange to me.

0

There are 0 best solutions below