Skip to content

Files

Latest commit

ae68a0c · Nov 20, 2019

History

History
77 lines (48 loc) · 1.74 KB

11.md

File metadata and controls

77 lines (48 loc) · 1.74 KB

作用域

原文: https://pythonspot.com/scope

作用域

变量只能到达定义它们的区域,这称为作用域。 将其视为可以使用变量的代码区域。 Python 支持全局变量(可在整个程序中使用)和局部变量。

默认情况下,函数中声明的所有变量都是局部变量。要访问函数内部的全局变量,必须明确定义“全局变量”。

示例

下面我们将研究局部变量和作用域的用法。它不起作用

#!/usr/bin/python

def 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 WORK

z = 3
f(3,2)

但这将:

#!/usr/bin/python

def f(x,y):
    z = 3
    print('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 function

f(3,2)

让我们进一步研究一下:

#!/usr/bin/python

def f(x,y,z):
    return x+y+z # this will return the sum because all variables are passed as parameters

sum = f(3,2,1)
print(sum)

调用函数

中的函数我们还可以从另一个函数中获取变量的内容:

#!/usr/bin/python

def highFive():
    return 5

def 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 above

result = f(3,2)
print(result)

如果在代码中的任何位置都可以访问变量,则称为全局变量。如果仅在作用域内部知道变量,则将其称为局部变量

下载 Python 练习