Geoff
Geoff

Reputation: 3

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)

Upvotes: 0

Views: 887

Answers (1)

XxJames07-
XxJames07-

Reputation: 1826

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

Upvotes: 2

Related Questions