Python 中变量的作用域

pythonserver side programmingprogramming更新于 2025/4/20 17:16:17

程序中的所有变量可能并非在该程序的所有位置都可访问。这取决于您声明变量的位置。

变量的作用域决定了您可以访问特定标识符的程序部分。Python 中有两种基本的变量作用域 −

  • 全局变量
  • 局部变量

全局变量与局部变量

在函数体内定义的变量具有局部作用域,而在函数体外定义的变量具有全局作用域。

这意味着局部变量只能在声明它们的函数内访问,而全局变量可在整个程序体内由所有函数访问。调用函数时,函数内部声明的变量将进入作用域。

示例

#!/usr/bin/python
total = 0; # 这是全局变量。
# 函数定义在这里
def sum( arg1, arg2 ):
   # 添加两个参数并返回它们。"
   total = arg1 + arg2; # 这里 total 是局部变量。
   print "函数内 local total : ", total
   return total;
# 现在您可以调用 sum 函数
sum( 10, 20 );
print "函数外 global total : ", total

输出

执行上述代码时,会产生以下结果 −

函数内 local total : 30
函数外 global total : 0

相关文章


有用资源