简体   繁体   English

Python class 变量初始化中的错误“名称'A'未定义”

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

This code works in the python command line.此代码适用于 python 命令行。 However, when compiling it in a module it gives the following error: "name 'A' is not defined."但是,在模块中编译它时会出现以下错误:“名称'A'未定义。”

>>> 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:这是b/c class尚未定义,因此您必须将c = Aa放在 class 之外,或者您可以这样做:

 class A:
     a = 2
 c = A.a
 print(c)

Output: Output:

2

or, as @Barman replied, you could do also:或者,正如@Barman 回答的那样,您也可以这样做:

 class A:
     a = 2
 A.c = A.a
 print(A.c)

Out:出去:

2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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