Home > Backend Development > Python Tutorial > python局部赋值的规则

python局部赋值的规则

WBOY
Release: 2016-06-06 11:27:58
Original
1340 people have browsed it

代码如下:


  myVar = 1

def myfunc():
    myVar += 1

myfunc()
  


   会提示错误:

UnboundlocalError: local variable 'myVar' referenced before assignment

Python提出如下假设:如果在函数体内的任何地方对变量赋值,则Python将名称添加到局部命名空间中。

语句myVar += 1对名称myVar赋值,则myVar是函数myfunc的局部命名空间的一部分,而它当前没有关联值,所以会产生错误。

解决方法:使用global语句

代码如下:


myVar = 1

def myfunc():
    global myVar
    myVar += 1

myfunc()

附作用域搜索规则:

L:本地的(Local)

E:封闭的(Eclosing)

G:全局的(Global)

B:内置的(Built-in) 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template