作用域
变量只能到达定义它们的区域,这称为作用域。 将其视为可以使用变量的代码区域。 Python 支持全局变量(可在整个程序中使用)和局部变量。
默认情况下,函数中声明的所有变量都是局部变量。要访问函数内部的全局变量,必须明确定义“全局变量”。
示例
下面我们将研究局部变量和作用域的用法。它不起作用:
#!/usr/bin/pythondef f(x,y):print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))print('x * y = ' + str(x*y))z = 4 # cannot reach z, so THIS WON'T WORKz = 3f(3,2)
但这将:
#!/usr/bin/pythondef f(x,y):z = 3print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))print('x * y = ' + str(x*y))print(z) # can reach because variable z is defined in the functionf(3,2)
让我们进一步研究一下:
#!/usr/bin/pythondef f(x,y,z):return x+y+z # this will return the sum because all variables are passed as parameterssum = f(3,2,1)print(sum)
调用函数
中的函数我们还可以从另一个函数中获取变量的内容:
#!/usr/bin/pythondef highFive():return 5def f(x,y):z = highFive() # we get the variable contents from highFive()return x+y+z # returns x+y+z. z is reachable becaue it is defined aboveresult = f(3,2)print(result)
如果在代码中的任何位置都可以访问变量,则称为全局变量。如果仅在作用域内部知道变量,则将其称为局部变量。
