Why can't I access the class in its own definition?

时间:2019-04-16 22:17:34

标签: python class

Why doesn't the following simple code work?

class A:
    a = A()

print(A.a)

The error I get is:

NameError: name 'A' is not defined

2 个答案:

答案 0 :(得分:2)

Because the class A is not attached to the name A in the namespace until the class definition is complete (denoted in python by a dedent). You can bind a variable to the class, however, with

class A:
    pass
A.a = A()
print(A.a)

Because by line 3, the name A exists and points to the class, whereas it does not by line 2.

答案 1 :(得分:2)

You cannot reference a class within its own definition since the class object does not actually get instantiated until its code block has been executed.

You can instead instantiate an object of the class and assign it to a class attribute of the class after the class has been defined:

class A:
    pass
A.a = A()
print(A.a)

This outputs:

<__main__.A object at 0x013C63B0>