Functions access to global variables

≡放荡痞女 提交于 2019-12-22 04:33:45

问题


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.



来源:https://stackoverflow.com/questions/22830923/functions-access-to-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!