Summary:
- Inner function: can access global variables without modifying them
- Inner function: if a global variable with the same name is modified, Python will treat it as a local variable
- Calling the variable name (e.g., print sum) before modifying the same-named global variable in an inner function raises Unbound-LocalError
The sum set in the program is a global variable, but there is no definition of sum in the function. According to Python's rules for accessing local and global variables: when searching for a variable, Python first searches from the local scope. If the variable is not found in the local scope, then Python looks for this variable in the global variables. If it is not found, an exception is thrown (NAMEERROR or Unbound-LocalError, depending on the Python version.)
If an inner function references a variable with the same name from an outer function or a global variable, and modifies this variable, then Python will treat it as a local variable. Also, because there is no definition or assignment of sum in the function, an error is reported.
From the following two programs, simply accessing or modifying a global variable does not report an error~
Access the global variable:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
sum=5
def add(a=1,b=3):
print a,b
print sum #仅仅访问
add(4,8)
print sum
The output result is:
4 8 5 5
Modifying a global variable with the same name is treated as a local variable:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
sum=5
def add(a=1,b=3):
print a,b
#内部函数有引用外部函数的同名变量或者全局变量,并且对这个变量有修改.那么python会认为它是一个局部变量
sum=b+a #在函数内部修改
print sum
add(4,8)
The output result is:
4 8 12
The following program will report an error because "if an inner function references a same-named variable from an outer function or a global variable, and modifies this variable, then Python will treat it as a local variable, and because there is no definition or assignment of sum in the function, so it reports an error:"
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
sum=5
def add(a=1,b=3):
print a,b
print sum #内部函数引用同名变量,并且修改这个变量。python会认为它是局部变量。因为在此处print之前,没有定义sum变量,所以会报错(建议与情况一比较,备注:此处只是比上例先print sum)
sum=b+a
print sum
add(4,8)
print sum
Error message:
4 8 Traceback (most recent call last): ... ... ... UnboundLocalError: local variable 'sum' referenced before assignment
When accessing a global variable in the program and needing to modify its value, you can use:globalkeyword, which declares this variable as a global variable in the function.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
sum=5
print '改变之前:sum=',sum
def add(a=1,b=3):
global sum
print 'add 函数中:sum=',sum
sum=b+a
print '函数中改变之后:sum= ',sum
add(4,8)
print '改变之后 sum=',sum
The output result is:
改变之前:sum= 5 add 函数中:sum= 5 函数中改变之后:sum= 12 改变之后 sum= 12
Original URL: https://blog.csdn.net/my2010sam/article/details/17735159