简体   繁体   中英

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

this is b/c the class is not defined yet, so you have to put the c = Aa 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM