python全局变量含义_Python函数全局变量?

本文探讨了Python中全局和局部变量的区别,特别是在函数内部的使用。通过示例说明了`global`关键字如何指示函数修改全局变量,以及不使用`global`时如何创建局部变量。同时,提到了变量作用域的重要性,并提醒读者避免过度依赖全局变量以减少混淆。
摘要由CSDN通过智能技术生成

在Python范围内,对未在该范围内声明的变量的任何赋值都会创建一个新的局部变量,除非该函数在函数中先前声明为引用具有关键字create_locally的全局范围变量。

让我们看一下你的伪代码的修改版本,看看会发生什么:

# Here, we're creating a variable 'x', in the __main__ scope.

x = 'None!'

def func_A():

# The below declaration lets the function know that we

# mean the global 'x' when we refer to that variable, not

# any local one

global x

x = 'A'

return x

def func_B():

# Here, we are somewhat mislead. We're actually involving two different

# variables named 'x'. One is local to func_B, the other is global.

# By calling func_A(), we do two things: we're reassigning the value

# of the GLOBAL x as part of func_A, and then taking that same value

# since it's returned by func_A, and assigning it to a LOCAL variable

# named 'x'.

x = func_A() # look at this as: x_local = func_A()

# Here, we're assigning the value of 'B' to the LOCAL x.

x = 'B' # look at this as: x_local = 'B'

return x # look at this as: return x_local

事实上,您可以使用名为access_only的变量重写所有create_locally,它的工作方式相同。

该命令仅对您的函数执行更改全局x值的操作的顺序很重要。 因此,在我们的示例中,顺序无关紧要,因为create_locally调用access_only.在此示例中,顺序确实很重要:

def a():

global foo

foo = 'A'

def b():

global foo

foo = 'B'

b()

a()

print foo

# prints 'A' because a() was the last function to modify 'foo'.

请注意,仅需要create_locally来修改全局对象。 您仍然可以在函数内访问它们,而无需声明access_only。因此,我们有:

x = 5

def access_only():

return x

# This returns whatever the global value of 'x' is

def modify():

global x

x = 'modified'

return x

# This function makes the global 'x' equal to 'modified', and then returns that value

def create_locally():

x = 'local!'

return x

# This function creates a new local variable named 'x', and sets it as 'local',

# and returns that. The global 'x' is untouched.

请注意create_locally和access_only - access_only之间的区别是访问全局x,尽管没有调用global,即使create_locally也没有使用global,它会创建一个本地副本,因为它正在分配一个值。

这里的混乱是你不应该使用全局变量的原因。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值