pythonfunctionvariablespanda3d

Accessing a variable defined inside a function Python


I am working on a project and I am running Python 2.7 and Panda3D v1.8.1. I have been unable to find out how to access a variable that was defined in a function. For the setup I have two files. One file manages events and the second file loads models. Here is an example of what I have:

class secondFile(object):

    def create_something(self):

        variable = loader.loadModel('myModel.bam')
        variable.setPos(123,1231,5)

In my first file I want to be able to access the variable so I can call a function when my character collides with it. I was reading other similar questions but none of the answers seemed to work for what I was trying to do.

DO = DirectObject()

def collideEventIn():
    print "Collision"

collisionHandler.addInPattern('%fn-into-%in')
DO.accept('character-into-variable', collideEventIn)

I have tried this:

class secondFile(object):

    def create_something(self):

        create_something.variable = loader.loadModel('myModel.bam')
        create_something.variable.setPos(123,1231,5)

Main file:

DO = DirectObject()

variable = secondFile().create_something.variable

def collideEventIn():
    print "Collision"

collisionHandler.addInPattern('%fn-into-%in')
DO.accept('character-into-variable', collideEventIn)

However it didnt seem to work.


Solution

  • Not sure if i'm interpreting your question correctly, but why don't you just return the variabe?

    def create_something(self):
        variable = loader.loadModel('myModel.bam')
        variable.setPos(123,1231,5)
        return variable
    

    And to access it in variable:

    variable = secondFile().create_something()
    

    If you want it to be more like OOP, you should bound variable to self:

    def create_something(self):
        self.variable = loader.loadModel('myModel.bam')
        self.variable.setPos(123,1231,5)
    

    And then, to access it:

    SF = secondFile()
    SF.create_something()
    variable = SF.variable