Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading