Functions access to global variables

2020-07-06 07:42发布

问题:

I am working on a text-based game to get more practice in Python. I turned my 'setup' part of the game into a function so I could minimize that function and to get rid of clutter, and so I could call it if I ever wanted to change some of the setup variables.

But when I put it all into a function, I realized that the function can't change global variables unless you do all of this extra stuff to let python know you are dealing with the global variable, and not some individual function variable.

The thing is, a function is the only way I know of to re-use your code, and that is all I really need, I do not need to use any parameters or anything special. So is there anything similar to functions that will allow me to re-use code, and will not make me almost double the length of my code to let it know it's a global variable?

回答1:

You can list several variables using the same global statement.

An example:

x = 34
y = 32

def f():
    global x,y
    x = 1
    y = 2

This way your list of global variables used within your function will can be contained in few lines.

Nevertheless, as @BrenBarn has stated in the comments above, if your function does little more than initializating variables, there is no need to use a function.



回答2:

Take a look at this.

Using a global variable inside a function is just as easy as adding global to the variable you want to use.