Charas-Project

  • Home
  • Help
  • Search
  • Calendar
  • Login
  • Register
*
Please login or register.

Login with username, password and session length
 

News:

Click here to join us on IRC (#charas on irc.freenode.net)!



  • Charas-Project »
  • Off-Topic »
  • Archive »
  • Really Old Stuff »
  • General programming »
  • How to use global variables in python
« previous next »
  • Print
Pages: [1]

Author Topic: How to use global variables in python  (Read 5600 times)

Offline war_machine1982

  • Initiate
  • *
  • Posts: 15
How to use global variables in python
« 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 :)
« Last Edit: April 26, 2009, 12:15:47 AM by war_machine1982 »
Logged

Offline Osmose

  • So freakin' inactive
  • Royal
  • *
  • Posts: 3,041
Re: How to use global variables in python
« Reply #1 on: April 26, 2009, 03:27:14 PM »
From what I've read, Python treats global variables similar to PHP:

Code: [Select]
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
Logged
Hrm.

Offline war_machine1982

  • Initiate
  • *
  • Posts: 15
Re: How to use global variables in python
« Reply #2 on: April 27, 2009, 09:38:24 PM »
Thanks. I'm just wondering what the ++ in globalVar does.

EDIT: Well, i tried using that, and it didn't work. Oh well.
« Last Edit: April 27, 2009, 09:50:56 PM by war_machine1982 »
Logged

Offline Osmose

  • So freakin' inactive
  • Royal
  • *
  • Posts: 3,041
Re: How to use global variables in python
« Reply #3 on: April 29, 2009, 03:57:44 AM »
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?
Logged
Hrm.

  • Print
Pages: [1]
« previous next »
  • Charas-Project »
  • Off-Topic »
  • Archive »
  • Really Old Stuff »
  • General programming »
  • How to use global variables in python
 

  • SMF 2.0.10 | SMF © 2015, Simple Machines
  • XHTML
  • 2O11
  • RSS
  • WAP2
  • Simple Machines Forum