Python全局/局部变量 [英] Python global/local variables
问题描述
为什么这段代码有效:
var = 0
def func(num):
print num
var = 1
if num!= 0:
func(num-1)
func(10)
但是这个给出了一个局部变量'var'在赋值之前被引用error:
var = 0
def func(num):
print num
var = var
if num $ = 0:
func(num-1)
func(10)
<因为在第一个代码中,你已经创建了一个局部变量 var
并使用了它的值,而在第二个代码中,您使用的是局部变量 var
,而没有定义它。
所以,如果你想使你的第二个函数需要声明: -
全局变量
在使用 var
之前的函数中。
def func(num):
p rint num
var = 1 < - #创建一个局部变量
如果num!= 0:
func(num-1)
鉴于此代码:
def func num):
print num
var = var <---#你在RHS上使用局部变量而不定义它
如果num!= 0:
func(num -1)
更新: -
然而,根据@ Tim的评论,你不应该在你的函数中使用
全局
变量。在使用它之前,确定你的变量,在local scope
中使用它。一般来说,你应该尝试limit
变量的范围到local
,甚至在本地
命名空间限制
局部变量的范围,因为这样你的代码将更容易理解。
您越增加变量的范围,外部资源就可以使用这些变量的可能性就越大,而不需要使用它。
p>Why does this code work:
var = 0 def func(num): print num var = 1 if num != 0: func(num-1) func(10)
but this one gives a "local variable 'var' referenced before assignment" error:
var = 0 def func(num): print num var = var if num != 0: func(num-1) func(10)
解决方案Because in the first code, you have created a local variable
var
and used its value, whereas in the 2nd code, you are using the local variablevar
, without defining it.So, if you want to make your 2nd function work, you need to declare : -
global var
in the function before using
var
.def func(num): print num var = 1 <-- # You create a local variable if num != 0: func(num-1)
Whereas in this code:
def func(num): print num var = var <--- # You are using the local variable on RHS without defining it if num != 0: func(num-1)
UPDATE: -
However, as per @Tim's comment, you should not use a
global
variable inside your functions. Rather deifine your variable before using it, to use it inlocal scope
. Generally, you should try tolimit
the scope of your variables tolocal
, and even inlocal
namespacelimit
the scope of local variables, because that way your code will be easier to understand.The more you increase the scope of your variables, the more are the chances of getting it used by the outside source, where it is not needed to be used.
这篇关于Python全局/局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!