0

I run the follow code ,it runs ok.

class A:
    def __init__(self):
        pass
class B:
    z = A()
    def __init__(self):
        pass
if __name__ == '__main__':
    pass

but when I place the "class A" behind the "class B",as follow:

class B:
    z = A()
    def __init__(self):
        pass

class A:
    def __init__(self):
        pass

if __name__ == '__main__':
    pass

I run it in PyCharm,it report the Traceback as follow :

Traceback (most recent call last):
  File "D:/PythonStudy/AB.py", line 4, in <module>
    class B:
  File "D:/PythonStudy/AB.py", line 5, in B
    z = A()
NameError: name 'A' is not defined

I am very confused why the "class A" not defined?

Sigma65535
  • 361
  • 4
  • 15
  • Uh... because it hasn't by that point? – Ignacio Vazquez-Abrams Oct 25 '17 at 02:10
  • Because it's not defined before you use it in `B`. Common sense: You can't drive your car before you have one to drive. You can't use a class before it is defined. At line 5, where you use `z = A()`, `A` has not been defined; `A` isn't defined until at least 5 lines later. – Ken White Oct 25 '17 at 02:11
  • this might help you understand better https://stackoverflow.com/questions/26193653/why-does-a-class-body-get-executed-at-definition-time – yash Oct 25 '17 at 02:23
  • @ Ken White , I wirite the code in Java,I found it run ok.So ,this is very surprising.Is the python unique phenomenon? – Sigma65535 Oct 25 '17 at 02:33

1 Answers1

0

A class, function, or any variable type is only accessible if it has been defined by the point you access it. always define anything before attempting to access it.

you may be confused by the fact that if you write a function that does the similar thing, like:

def a():
    return l * 2

l=6
b=a()

and it will work fine, however if you try in the shell:

>>> class a:
       print('hi')

you will get:

hi
>>>

before you create a instance. this is because when you define a class in python, the code is run immediately, and a function's code is only run when called.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
Michael
  • 436
  • 3
  • 11