📜  Python变量范围

📅  最后修改于: 2022-05-13 01:55:07.204000             🧑  作者: Mango

Python变量范围

在Python中,变量是存储数据值的容器。它们是内存中对象的引用或指针,这意味着每当将变量分配给实例时,它都会映射到该实例。与 C/C++/ Java等其他语言不同, Python不是“静态类型的”。我们不需要在使用它们之前声明变量或声明它们的类型。一个变量在我们第一次给它赋值的那一刻就被创建了。
例子:

Python3
# Python program to demonstrate
# variable assignment
   
# An integer assignment
age = 45                     
   
# A floating point
salary = 1456.8            
   
# A string  
name = "John"             
   
print(age)
print(salary)
print(name)


Python3
# This function uses global variable s
def f(): 
    print(s)
   
# Global scope
s = "I love Geeksforgeeks"
f()


Python3
# This function has a variable with
# name same as s.
def f(): 
    s = "Me too."
    print(s)
   
# Global scope
s = "I love Geeksforgeeks"
f()
print(s)


Python3
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 Geeksforgeeks"
f()
print(s)


Python3
# This function modifies global variable 's'
def f():
    global s
    print(s)
    s = "Look for Geeksforgeeks Python Section"
    print(s)
   
# Global Scope
s = "Python is great !"
f()
print(s)


Python3
# 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)


Python3
# 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()


输出:

45
1456.8
John

注意:要了解有关变量的更多信息,请单击此处。

变量范围

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

全局变量和局部变量

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

Python3

# This function uses global variable s
def f(): 
    print(s)
   
# Global scope
s = "I love Geeksforgeeks"
f()

输出:

I love Geeksforgeeks

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

Python3

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

输出:

Me too.
I love Geeksforgeeks

在我们调用函数f() 之前,变量 s 被定义为字符串“I love Geeksforgeeks”。 f() 中唯一的语句是 print(s) 语句。由于没有本地 s,因此将使用来自全局 s 的值。
问题是,如果我们在函数f() 中改变 s 的值会发生什么?它会影响全局吗?我们在下面的代码中对其进行测试:

Python3

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 Geeksforgeeks"
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,如以下示例所示:

Python3

# This function modifies global variable 's'
def f():
    global s
    print(s)
    s = "Look for Geeksforgeeks Python Section"
    print(s)
   
# Global Scope
s = "Python is great !"
f()
print(s)

输出:

Python is great!
Look for Geeksforgeeks Python Section
Look for Geeksforgeeks Python Section

请考虑以下示例以更好地理解该主题。

Python3

# 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中,在嵌套函数的情况下使用 nonlocal 关键字。此关键字的作用类似于 global,但不是 global,此关键字声明一个变量以指向外部封闭函数的变量,以防嵌套函数。
例子:

Python3

# 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