0

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)
4
  • The name A isn't defined until after the class block is finished. So you can't reference it while defining the class. Commented Jan 25, 2022 at 22:08
  • I suspect in your interactive session you had previously defined the A class. So you were using the old value of A.a. Commented Jan 25, 2022 at 22:08
  • Ok, that makes sense. But, why does it work in the command line? Commented Jan 25, 2022 at 22:13
  • @Barmar Thanks. You are correct. I reset my command line, and then it generated the same error. Commented Jan 25, 2022 at 22:16

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Or A.c = A.a to do what he was trying to do.
@Barmar Ya, I get it now. I need to define a class variable without initializing it. Then, if I want to use the other class variables to assign to this class variable, I can do later in my code by using the class name like this: A.b = A.a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.