Charas-Project
Off-Topic => Really Old Stuff => Archive => General programming => Topic started by: war_machine1982 on April 23, 2009, 12:08:19 AM
-
Hello. I was having trouble using global vars in Python. I tried defining them at the start of the program, but that didn't work when i wanted to change then inside a class or function. Then i defined them using the global statement, and tried again, but still no luck. Can someone help me please?
EDIT: Whatever. I'll just use a main class and derive more from it. Solves the problem. If anyone reads this, feel free to post your help. Thanks :)
-
From what I've read, Python treats global variables similar to PHP:
globalVar = 2
def somefunction():
global globalVar
localVar = 2
globalVar++
Barring me not knowing a whole lot of Python syntax, that is how you use a global variable; you define it outside of a class or function to set it at global scope, and any functions that wish to use it must first declare it global as seen above, otherwise it will just create a local variable named the same as your global variable.
Of course, you should always think before you use a global variable anyway, as they're messy if they start to pile up. :P
-
Thanks. I'm just wondering what the ++ in globalVar does.
EDIT: Well, i tried using that, and it didn't work. Oh well.
-
Ah, good question. In most languages, ++ adds one to whatever variable it's stuck on, so if globalVar = 0, then globalVar++ would make globalVar = 1, and so on.
Also, how did it not work? Was it simply the ++ or the actual global part?