0

This is not a problem with my code, but rather a general question about Python 3.

Say you had a game, which had 4 parts to it, and the first part (main.py) declares a variable that say, part 2 needs to run itself. Would you be able to declare that variable, then import part2 (That needs the variable to run smoothly) and have the variable carry on from main.py to part2.py after importing part2.py into main.py.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
TheUnknown
  • 33
  • 3
  • 1
    so whats the problem ? and what you try ? – Mazdak Oct 28 '14 at 16:22
  • My game has 4 parts to it and in main.py has a variable called z. In part2.py when i run it an error points to this:if g > z or g < 0: saying that it is refrenced before assignment. I have tried making it global and that does not work either. – TheUnknown Oct 28 '14 at 16:28
  • 2
    I have a feeling that you might not know how `import` works. What do you mean with "when I run part2.py"? – Matthias Oct 28 '14 at 16:31
  • you can not access to a variable from separate file you need to import the function that the variable is in, or ... anyway you need to show your codes ! – Mazdak Oct 28 '14 at 16:32
  • related: [Python: How to make a cross-module variable?](http://stackoverflow.com/q/142545/4279). – jfs Oct 28 '14 at 17:37
  • @ J.F. Sebastian, that related help a lot so thanks for putting that up. – TheUnknown Oct 28 '14 at 18:19

2 Answers2

0

here is a simple example you can try out

file1.py

import sys
sys.argv = "Yellow" #probably not a really great Idea but should suffice

from file2 import sys as sys2
print "Imported argv from file2",sys2.argv
print "Same thing? ", sys is sys2

file2.py

import sys
print "My argv f2:",sys.argv
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

If you want to use the variable once you can do this.

# part2.py

def scream():
 print(sound)  

# part1.py
import part2

if __name__=="__main__":
    part2.sound = "Yoooo"
    part2.scream()

#Output:
Yoooo

If you want to be able to change the variable later. You can create a property
Or simply do this:

# part2.py
# gvars is defined later
def scream():
 print(gvars.sound)


# part1.py
import part2

class GameVariables:
    pass

if __name__=="__main__":
    gvars = GameVariables()
    part2.gvars = gvars
    gvars.sound = "Yooo"
    part2.scream()
    gvars.sound = "Whaa"
    part2.scream()

#output
Yooo
Whaa
Rui Botelho
  • 752
  • 1
  • 5
  • 18