[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Declaring variables in function as if at code's line-level



It's not clear at all what you mean by "line-level". It sounds like you mean variables that are at the global scope, ie, you want to declare global variables. The answer is you use the "global" keyword within the function. Sorry if this seems like a lot of extra work, but I doubt you'll find much sympathy, since what you're doing is discouraged by most python users.

One other possibility that I doubt you'll prefer is declaring a global object, and every time you want to declare a variable on the global scope, you set it to a member of that object. To wit:

class globalstuff: pass

def function1():
    globalstuff.x = 100

def function2():
    print globalstuff.x

Don't freak out at the fact that I used the "class" keyword. globalstuff is not what you normally think of as a class. That's just how you declare a namespace in python.

If "line-level" means something other than global variables, please explain in more detail.

-Christopher

On Sat, Mar 10, 2012 at 3:39 PM, Brian Brown <brobab@xxxxxxxxx> wrote:
My plan is to make my program "function-oriented."
(Much less complicated than creating unnecessary classes and modules
(each with more functions) for something as simple as a small game
with just integer variables and string variables.)
Only using "line-level" and "function-level" with "global variables"
makes everything simple and easy. I don't understand why there's so
much hype about creating a new "class" or "module" whenever possible--
as if it will somehow magically make a program execute with more
satisfactory results.

Thank you Ciro, but yes, I think you didn't answer my question.


On 3/10/12, Ciro Duran <ciro.duran@xxxxxxxxx> wrote:
> You can just declare your variables inside a function and their scope will
> only reach inside that function.
>
> If you declare module variables (or global variables, if you fancy that
> name more) you can refer them inside functions without adding anything. But
> if you want to assig something to the variable (eg. Create an object) you
> must specify the global keyword at the beginning of the function.
>
> Sorry if I didn't get the point of your question.
>
> Ciro
>
> El sábado 10 de marzo de 2012, Brian Brown <brobab@xxxxxxxxx> escribió:
>> Hi pygame users, just a simple question-- How can one cause variables
>> at "function-level" to behave like variables at "line-level"? (With
>> basic python code) I just want to avoid using "global" over and over
>> again (in many different functions) while I want to declare, use, and
>> delete all my game's variables inside functions.Thanks.
>> Matt
>>
>