Python code error - NameError: name is not defined

Hi experts!

I’ve made a pretty simple example in Python. I don’t understand why this code wont work? I got the error:

DirectStart: Starting the game.
Warning: DirectNotify: category ‘Interval’ already exists
Known pipe types:
wdxGraphicsPipe8
(3 aux display modules not yet loaded.)
Traceback (most recent call last):
File “StartGame.py”, line 7, in ?
class Start:
File “StartGame.py”, line 8, in Start
g = LoadGraphics()
NameError: name ‘LoadGraphics’ is not defined

Here is the code:


import direct.directbase.DirectStart
from direct.task import Task
from direct.interval.IntervalGlobal import *
import math
import EventTest

class Start:
    g = LoadGraphics()
    g.LoadEnvironment()
    g.LoadModelX()
    
    taskMgr.add(LoadEnvironment, "LoadEnvironment")
    taskMgr.add(LoadModelX, "LoadModelX")
    
    e = EventTest.EventTest()
    
    run()
    
class LoadGraphics:
    
    def LoadEnvironment(task):
        environ = loader.loadModel("Models/Environment")
        environ.reparentTo(render)
        environ.setPos(-8,42,0) 
    
    def LoadModelX(task):
        c = loader.loadModel("Models/Character")
        c.reparentTo(render)
        c.setPos(-8,-100,10)
        
       ....................

What is wrong by writing: g = LoadGraphics()???

Because you have not enclosed the code within class Start within a function, it will be executed immediately when the file is imported–before it finishes reading the rest of the file, and therefore before it has encountered the definition of the LoadGraphics class.

You can simply reverse the order of your two classes, and that will solve your problem. However, it is unusual to define code directly within a class like this; maybe you meant to define this within a method, like init() for instance?

David