Home > OS >  Python Error "name 'A' is not defined" in class variable initialization
Python Error "name 'A' is not defined" in class variable initialization

Time:01-26

This code works in the python command line. However, when compiling it in a module it gives the following error: "name 'A' is not defined."

>>> class A:
...     a = 2
...     c = A.a
... 
>>> A.c
2
class A:
    a = 2
    c = A.a

NameError: name 'A' is not defined

CodePudding user response:

this is b/c the class is not defined yet, so you have to put the c = A.a outside of the class, or you could do:

 class A:
     a = 2
 c = A.a
 print(c)

Output:

2

or, as @Barman replied, you could do also:

 class A:
     a = 2
 A.c = A.a
 print(A.c)

Out:

2
  •  Tags:  
  • Related