Search code examples
pythonvariablesstatic

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


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

I found a better solution. As shown below, a static variable is available for the initialization of another static variable. The code below compiles fine.

class A:
    a = 2
    b = a

c = A()
print(c.b)

Solution

  • 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