Python 中局部变量和全局变量的规则是什么?


Python 中变量的作用域分为两种:局部作用域和全局作用域。作用域定义为变量在一个区域内的可访问性。在了解规则之前,让我们先了解局部和全局作用域。

局部作用域

示例

这定义了变量的局部作用域,即它只能在其定义的函数中访问。局部作用域的变量在函数外部无法访问。让我们来看一个例子:

# Variable with local scope can only be access inside the function def example(): i = 5 print(i) # An error is thrown if the variabke with local scope # is accessed outside the function # print(i) # Calling the example() function example()

输出

5

全局作用域

示例

如果一个变量可以在任何地方访问,即在函数内部和外部都可以访问,则称为全局作用域。让我们来看一个例子:

# Variable i = 10 # Function def example(): print(i) print(i) # The same variable accessible outside the function # Calling the example() function example() # The same variable accessible outside print(i)

输出

10
10
10

局部和全局变量的规则

以下是规则:

  • 仅在函数内部引用的变量隐式为全局变量。

  • 如果在函数体的任何地方为变量赋值,则除非显式声明为全局变量,否则它被认为是局部变量。

  • 局部作用域的变量只能在其定义的函数中访问。

  • 全局作用域的变量可以在函数内部和外部访问。

更新于:2022年9月16日

2K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.