简体   繁体   English

Python中的全局变量和局部变量

[英]Global and local variables in Python

I am learning Python. 我正在学习Python。 A book on Python 3 says the following code should work fine: 一本关于Python 3的书说以下代码应该可以正常工作:

def funky():
    print(myvar)
    myvar = 20
    print(myvar)

myvar = 10
funky()

But when I run it in Python 3.3, I got the 但是当我在Python 3.3中运行它时,我得到了

UnboundLocalError: local variable 'myvar' referenced before assignment

error. 错误。 My understanding is that the first print(myvar) in funky should be 10 since it's a global variable. 我的理解是, funky的第一个print(myvar)应该是10,因为它是一个全局变量。 The second print(myvar) should be 20 since a local myvar is defined to be 20. What is going on here? 第二个print(myvar)应该是20,因为当地的myvar被定义为20.这里发生了什么? Please help clarify. 请帮忙澄清一下。

You need to call global in your function before assigning a value. 在分配值之前,需要在函数中调用global

def funky():
    global myvar
    print(myvar)
    myvar = 20
    print(myvar)

myvar = 10
funky()

Note that you can print the value without calling global because you can access global variables without using global , but attempting to assign a value will require it. 请注意,您可以在不调用全局的情况下打印值,因为您可以在不使用global变量的情况下访问全局变量,但尝试分配值将需要它。

From the docs : 来自文档

Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use. 程序文本中每次出现的名称都是指在包含该用途的最内层功能块中建立的该名称的绑定。

It means that unless you declare it global or nonlocal (nested functions) then myvar is a local variable or a free variable (if myvar is not defined in the function). 这意味着除非您将其声明为global或非nonlocal (嵌套函数),否则myvar是局部变量或自由变量(如果myvar未在函数中定义)。

The book is incorrect. 这本书不对。 Within the same block the name represents the same variable (local variable myvar in your example, you can't use it until you define it even if there is a global variable with the same name). 在同一个块中,名称表示相同的变量(示例中的局部变量myvar ,即使存在具有相同名称的全局变量,也不能使用它直到定义它)。 Also you can change values outside a function ie, the text at the end of page 65 is also incorrect . 还可以更改函数外部的值,即第65页末尾的文本也不正确 The following works: 以下作品:

def funky(): # local
    myvar = 20 
    print(myvar) # -> 20
myvar = 10 # global and/or local (outside funky())
funky()
print(myvar) # -> 10 (note: the same)

def funky(): # global
    global myvar
    print(myvar) # -> 10
    myvar = 20
myvar = 10
funky() 
print(myvar) # -> 20 (note: changed)

def funky(): # free (global if funky is not nested inside an outer function)
    print(myvar) # -> 10
myvar = 10
funky() 

def outer():
    def funky():  # nonlocal
        nonlocal myvar
        print(myvar) # -> 5
        myvar = 20
    myvar = 5 # local
    funky()
    print(myvar) # -> 20 (note: changed)
outer()

Python "assumes" that we want a local variable due to the assignment to myvar inside of funky(), so the first print statement throws ## UnboundLocalError: local variable 'myvar' referenced before assignment ## error message. Python“假设”我们想要一个局部变量,因为在funky()中分配了myvar,所以第一个print语句抛出## UnboundLocalError:在赋值##错误消息之前引用的局部变量'myvar'。 Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. 在函数内部更改或创建的任何变量都是本地的,如果它尚未声明为全局变量。 To tell Python, that we want to use the global variable, we have to use the keyword "global", as can be seen in the following example: 要告诉Python,我们要使用全局变量,我们必须使用关键字“global”,如以下示例所示:

def f():
  global s
  print s
  s = "That's clear."
  print s 


s = "Python is great!" 
f()
print s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM