函数访问全局变量 [英] Functions access to global variables

查看:125
本文介绍了函数访问全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个基于文本的游戏,以在Python中获得更多的练习.我将游戏的设置"部分变成了一个函数,这样我就可以最小化该函数并消除混乱,因此,如果我想更改某些设置变量,可以调用它.

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.

但是当我将其全部放入一个函数中时,我意识到该函数无法更改全局变量,除非您做所有这些额外的工作以使python知道您正在处理全局变量,而不是某些单独的函数变量

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?

推荐答案

您可以使用同一global语句列出多个变量.

You can list several variables using the same global statement.

一个例子:

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.

尽管如此,正如@BrenBarn在上面的评论中所述,如果您的函数只需要初始化变量,则无需使用函数.

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.

这篇关于函数访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆