Let me instead simply show you two ways in which it can be done:
Approach One: A Common File
Here, we create a âcommonâ script-file that holds a reference to our game-class, and which can be imported to provide access to that class:
The common-file
class Common():
# Being placed outside of any method, but inside
# the class-definition, this variable belongs to the class,
# and not to a specific instance.
game = None
Some arbitrary Python-file, such as your model-loader
# Import the Common class, so that we have access to its contents
from Common import Common
# Note that this class doesn't inherit from ShowBase!
class SomeOtherClass()
def __init__(self):
# Load a model.
# To do this, we access the "game"-class as stored in
# the "Common" class, and from there access the
# "loader" held by that "game"-class
self.modelObject = Common.game.loader.loadModel("someModelFile")
The main âgameâ class
from direct.showbase.ShowBase import ShowBase
# Import the "Common" class
from Common import Common
from SomeOtherClass import SomeOtherClass
class MyGame(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# Assign this object to the variable in the Common-class
Common.game = self
# Use "SomeOtherClass"
someObject = SomeOtherClass("aModelFile")
Approach Two: Passing Parameters
Here we simply pass a reference to our âgameâ class into the other class, thus giving us access to that class.
Some arbitrary Python-file, such as your model-loader
# Note that this class doesn't inherit from ShowBase!
class SomeOtherClass()
def __init__(self, modelFile, gameReference):
# Load a model.
# To do this, we access "loader" from the "gameReference" object,
# which is presumed to hold a reference to an object of class "MyGame"
self.modelObject = gameReference.loader.loadModel(modelFile)
The main âgameâ class
from direct.showbase.ShowBase import ShowBase
from SomeOtherClass import SomeOtherClass
class MyGame(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# Use "SomeOtherClass"
# Here we pass in not only the model-file, but
# this "MyGame"-object itself!
someObject = SomeOtherClass("aModelFile", self)
Thoughts
The âCommonâ-file approach is arguably a little more complicated. However, conversely, the âparameterâ approach can become a little clunky as you start passing parameters here there and everywhere.
Personally, I recommend the âCommonâ-file approach: it seems to work fairly well, and to do so elegantly and conveniently, I feel.