Import script in another one

Hello all…
I searched for the answer of the question and found nothing

I have a file called sphere.py and code inside it is:

import direct.directbase.DirectStart
class sphereModel():
  sphere=loader.loadModel("models/sphere")
  sphere.reparentTo(render)
  sphere.setPos(0,0,2)
run()

another file called cube.py and I want to make the file sphere.py to be loaded from it and change the position of the model found in sphere.py
code inside it is:

import direct.directbase.DirectStart
class cubeModel():
   cube=loader.loadModel("models/cube")
   cube.reparentTo(render)
   cube.setPos(0,0,0)

from sphere.py import sphereModel
sphere.setPos(5,2,4)
run()

the two models now are loaded successfully but the sphere model position remained without changing to the new value…so what is the problem???
I hope it’s obvious, if not I’ll send the files

Thanks in advance

There are a few problems here.

  1. run() should only be called once. You might have a main script (example: “game.py”) that imports sphere and cube classes and then calls run(). When you import sphere, it is calling run() and the game is now executing and it will not pass this point until the game window is closed. Even if it did you would get an error on sphere.setPos(5,2,4) because:

  2. You are not using classes properly, you are treating them like a function. The point of classes is to be able to create instances of them. Code that executes when an instance of a class is created should be in an init function of the class, thus it would look something like this:

class cubeModel():
    def __init__(self):
        self.node = loader.loadModel('models/cube')
        self.node.reparentTo(render)
        self.node.setPos(0, 0, 0)

This way the code doesn’t get executed until you create an instance of the class. You would do that in your main script like this:

import direct.directbase.DirectStart
from sphere import sphereModel

mysphere = sphereModel()
mysphere.node.setPos(5, 2, 4)
anothersphere = sphereModel()
anothersphere.node.setPos(1, 5, 3)
run()

You can make as many instances of sphereModel class as you want.

I would recommend reading up on how to use classes properly if you are going to use them.

You solved my problem…
First I know I wrote the class in a wrong way but because I found that it will not make sense
My problem was in this code:

import direct.directbase.DirectStart 
class cubeModel(): 
   cube=loader.loadModel("models/cube") 
   cube.reparentTo(render) 
   cube.setPos(0,0,0) 

from sphere.py import sphereModel 
sphere.setPos(5,2,4) 
run() 

that I wrote sphere.setPos(5,2,4) not sphereModel.sphere.setPos(5,2,4) and also not to wrote run() in the sphereModel script
Now I works fine…Thank you so much