Python - 如何使一个局部变量(在一个函数内)全局 [英] Python - How to make a local variable (inside a function) global

查看:365
本文介绍了Python - 如何使一个局部变量(在一个函数内)全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

在创建它们的函数中使用全局变量


我正在使用函数,以便我的程序不会混乱,但我不知道如何将局部变量编入全局。 / p>

解决方案

以下是两种实现同一功能的方法: strong>使用参数和返回(推荐)
$ b

  def other_function(参数):
返回参数+ 5

def main_function():
x = 10
print x
x = other_function(x)
print x

当您运行 main_function 时,您将得到以下输出

 >>> 10 
>>> 15

使用全局变量(从不这样做)

  x = 0#x的初始值,全局范围
$ b $ def other_function():
全局x
x = x + 5

def main_function():
print x#只需打印 - 无需声明全局但
全局x#因此,我们可以更改全局x
x = 10
print x
other_function()
print x

现在您将获得:

 >>> 0#初始全局值
>>> 10#现在我们在`main_function()`
>>>中设置了10。 15#现在我们在`other_function()`


中加了5

Possible Duplicate:
Using global variables in a function other than the one that created them

I'm using functions so that my program won't be a mess but I don't know how to make a local variable into global.

解决方案

Here are two methods to achieve the same thing:

Using parameters and return (recommended)

def other_function(parameter):
    return parameter + 5

def main_function():
    x = 10
    print x    
    x = other_function(x)
    print x

When you run main_function, you'll get the following output

>>> 10
>>> 15

Using globals (never do this)

x = 0   # The initial value of x, with global scope

def other_function():
    global x
    x = x + 5

def main_function():
    print x    # Just printing - no need to declare global yet
    global x   # So we can change the global x
    x = 10
    print x
    other_function()
    print x

Now you will get:

>>> 0    # Initial global value
>>> 10   # Now we've set it to 10 in `main_function()`
>>> 15   # Now we've added 5 in `other_function()`

这篇关于Python - 如何使一个局部变量(在一个函数内)全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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