Python局部变量和全局变量

在Python中,变量是存储数据值的容器。与 C/C++/JAVA 等其他语言不同,Python不是“静态类型”。我们不需要在使用变量之前声明它们或声明它们的类型。当我们第一次给变量赋值时,变量就被创建了。 

Python 作用域变量

我们可以找到变量并在需要时访问它的位置称为变量的范围

Python 局部变量

局部变量是在函数内初始化的变量,并且对于该函数来说是唯一的。无法在函数外部访问它。让我们看看如何创建局部变量。

def f():

	# local variable
	s = "I love Jkhxw"
	print(s)


# Driver code
f()

输出:

I love Jkhxw

如果我们尝试在函数外部使用这个局部变量,那么让我们看看会发生什么。

def f():
	
	# local variable
	s = "I love Jkhxw"
	print("Inside Function:", s)

# Driver code
f()
print(s)

输出:

NameError: name 's' is not defined

Python 全局变量

全局变量是在任何函数外部定义和声明的变量,并且未指定给任何函数。它们可以被程序的任何部分使用。

# This function uses global variable s
def f():
	print(s)


# Global scope
s = "I love Jkhxw"
f()

输出:

I love Jkhxw

同名的全局变量和局部变量

现在假设在函数范围内定义了一个具有相同名称的变量,那么它将仅打印函数内部给定的值,而不是全局值。

# This function has a variable with
# name same as s.
def f():
	s = "Me too."
	print(s)

# Global scope
s = "I love Jkhxw"
f()
print(s)

输出:

Me too.
I love Jkhxw

在我们调用函数 f() 之前,变量 s 被定义为字符串“I love Jkhxw”。f() 中唯一的语句是 print(s) 语句。由于没有本地变量,因此将使用全局变量的值。问题是,如果我们改变函数 f() 内部 s 的值会发生什么?

def f():
	print(s)

	# This program will NOT show error
	# if we comment below line.
	s = "Me too."

	print(s)


# Global scope
s = "I love Jkhxw"
f()
print(s)

输出:

Traceback (most recent call last):
  File "/home/370cac45bae7f1e6096520b7a0edb604.py", line 13, in 
    f() 
  File "/home/370cac45bae7f1e6096520b7a0edb604.py", line 3, in f
    print(s) 
UnboundLocalError: local variable 's' referenced before assignment

为了使上面的程序运行,我们需要使用global关键字。如果我们想要进行赋值/更改它们,我们只需要在函数中使用 global 关键字。打印和访问不需要全局。为什么?由于 f() 内部对 s 的赋值,Python“假设”我们需要一个局部变量,因此第一个 print 语句会抛出此错误消息。如果尚未将函数声明为全局变量,则在函数内部更改或创建的任何变量都是局部变量。 

为了告诉Python,我们想要使用全局变量,我们必须使用关键字global,如下所示:

# This function modifies global variable 's'
def f():
	global s
	print(s)
	s = "Look for Jkhxw Python Section"
	print(s)


# Global Scope
s = "Python is great !"
f()
print(s)

输出:

Python is great!
Look for Jkhxw Python Section
Look for Jkhxw Python Section

请看以下示例以更好地理解全局变量和局部变量。

# Python program to demonstrate
# scope of variable

a = 1

# Uses global because there is no local 'a'
def f():
	print('Inside f() : ', a)

# Variable 'a' is redefined as a local
def g():	
	a = 2
	print('Inside g() : ', a)

# Uses global keyword to modify global 'a'
def h():	
	global a
	a = 3
	print('Inside h() : ', a)

# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)

输出:

global :  1
Inside f() :  1
global :  1
Inside g() :  2
global :  1
Inside h() :  3
global :  3

Python 非本地关键字

在 Python 中,nonlocal 关键字用于嵌套函数的情况。该关键字的工作方式与 global 类似,但与全局不同,该关键字声明一个变量以指向外部封闭函数的变量(在嵌套函数的情况下)。

# Python program to demonstrate
# nonlocal keyword

print("Value of a using nonlocal is : ", end="")


def outer():
	a = 5

	def inner():
		nonlocal a
		a = 10
	inner()
	print(a)


outer()

# demonstrating without non local
# inner loop not changing the value of outer a
# prints 5
print("Value of a without using nonlocal is : ", end="")


def outer():
	a = 5

	def inner():
		a = 10
	inner()
	print(a)


outer()

输出:

Value of a using nonlocal is : 10
Value of a without using nonlocal is : 5