Search code examples
pythonpython-3.xnameerror

NameError: name 'Class' is not defined


When I compile I get this error:

Traceback (most recent call last):
  File "c:/Users/dvdpd/Desktop/ProjectStage/Main.py", line 1, in <module>
    class Main:
  File "c:/Users/dvdpd/Desktop/ProjectStage/Main.py", line 6, in Main
    test = Reading()
NameError: name 'Reading' is not defined

Code:

class Main:
    print("Welcome.\n\n")
    test = Reading()
    print(test.openFile)


class Reading:
    def __init__(self):
        pass

    def openFile(self):
        f = open('c:/Users/dvdpd/Desktop/Example.txt')
        print(f.readline())
        f.close()

I can't use the class Reading and I don't know why. Main and Reading are in the same file so I think I don't need an import.


Solution

  • Forward declaration doesn't work in Python. So you'll get an error only if you create an object of the Main class as follows:

    class Main:
        def __init__(self):
            print("Welcome.\n\n")
            test = Reading()
            print(test.openFile)
    
    # Main() # This will NOT work
    
    class Reading:
        def __init__(self):
            pass
    
        def openFile(self):
            f = open('c:/Users/dvdpd/Desktop/Example.txt')
            print(f.readline())
            f.close()
    
    # Main() # This WILL work