Python中的变量范围

Python中的变量范围

Python语言中的变量是各种数据值和数据结构的存储单位。当一个变量被分配给任何Python对象时,它就指向那个对象,因为它们是内存位置中那个特定对象的引用,或者说是一个指针。Python编程语言不是 “静态类型”,与其他语言如C/C++/JAVA不同。变量在使用前不需要声明其类型或初始值。当一个变量最初被赋予一个值时,它被认为已经形成。

代码

# Python program to show how variables are assigned to the data values

# Assigning a variable name to an integer
integer = 45                     

# Assigning a variable name to a floating point number
floating = 1456.8           

# Assigning a variable name to a string
string = "John"             

print("This value is stored in the variable 'integer':- ", integer)
print("This value is stored in the variable 'floating':- ", floating)
print("This value is stored in the variable 'string':- ", string)

输出:

This value is stored in the variable 'integer':-  45
This value is stored in the variable 'floating':-  1456.8
This value is stored in the variable 'string':-  John

变量的范围

一个Python变量的范围指的是我们可以找到它的地方,如果有必要,可以访问它。

全局和局部变量

全局变量是指我们在任何函数之外声明和定义的变量,但不是专门针对任何函数的。程序的任何部分都可以使用它们。

代码

# Python program to show how any function can use global variables

# Declaring a global variable
a = 2

# Accessing the global variable in the main function
print("This is in the main function:- ", a)

# Defining a function that uses the global variable
def f1():
    print("This is in function 'f1()':- ", a)

# Defining another function that uses the global variable
def f2():
    print("This is in function 'f2()':- ", a)

# Calling the functions
f1()
f2()

输出:

This is in the main function:- 
2
This is in function 'f1()':- 
2
This is in function 'f2()':- 
2

假设一个变量被定义在该函数的局部范围内,并且与全局变量的名称相同。在这种情况下,它将只显示在该特定函数内提供给该变量的值,而不是在全局范围内分配的值。

代码

# Python program to show function accesses the variable value that is in the function's scope

# Declaring a global variable
a = "This is assigned in the global scope."

# Defining a function that has a variable having the name same as the global variable
def func():
    a = "This is defined inside the function."
    print(a)

# Calling the function
func()

输出:

This is defined inside the function.

在定义函数func()之前,变量’a’被分配到一个字符串中,该字符串指出:”这是在全局范围内分配的。”。函数func()的print(a)语句将首先在其局部范围内搜索变量’a’。由于已经有一个变量’a’分配给了一个不同的字符串,该函数将打印这个变量的值,而不会进入全局范围。在这种情况下,该函数不会使用全局范围内的变量’a’的值。

下一个问题是,在函数’func()’中修改变量’a’的值会有什么结果。它是否也会对全局变量’a’产生影响?下面的代码片断用来测试。

代码

# Python program to show function accesses the variable value that is in the function's scope

# Declaring a global variable
a = "This is assigned in the global scope."

# Defining a function that has a variable having the name same as the global variable
def func():
    a = "This is defined inside the function."
    print("Accessed in the local scope of function:- ", a)

# Calling the function
func()

# Accessing the variable a in the global scope after changing its value inside the function
print("Accessed in the global scope:- ", a)

输出:

Accessed in the local scope of function:-  This is defined inside the function.
Accessed in the global scope:-  This is assigned in the global scope.

我们必须使用Python全局关键字来使前面的程序发挥作用。只有在进行赋值或改变变量值时,我们才需要在函数内部使用Python global关键字。在显示和访问存在于全局范围内的变量时,不需要使用 global 关键字。为什么呢?因为在 func() 中对变量 ‘a’ 的赋值,Python “假定 “我们想要访问局部变量,这就是为什么最初的 print 命令会返回局部范围内的变量值。如果一个变量在函数中被修改或赋值,而没有被定义为全局变量,它就被认为是一个局部变量。下面的例子演示了如何使用 global 关键字来指示 Python 解释器,我们希望修改全局变量。

代码

# Python program to show function accesses the variable value that is in the function's scope

# Declaring a global variable
a = "This is assigned in the global scope."

# Defining a function that uses the global keyword before assigning a new value to the global variable
def func():
    global a
    a = "This is defined inside the function."

print("Accessed in the local scope of function:- ", a)

# Calling the function
func()

# Accessing the variable a in the global scope after changing its value inside the function
print("Accessed in the global scope:- ", a)

输出:

Accessed in the local scope of function:-  This is defined inside the function.
Accessed in the global scope:-  This is defined inside the function.

总结全局局部变量的范围。

代码

# Python program to summarise the global and local variable scope.

# Defining a variable in the global scope
a = 'in the global scope'

# This function will print the global variable because there does not exist any local variable 'a'
def func():
    print('Inside func(): ', a)

# This function will print the value assigned to the local variable 'a'
# Because we are not using the global keyword
def local():    
    a = 'inside function local()'
    print('Inside local(): ', a)

# This function will modify the global variable because we are using the global keyword
def global_():    
    global a
    a = 'changed inside function global_()'
    print('Inside global_() : ', a)

# Calling the functions
# Value of 'a' in global scope after each function call
print('global: ', a)
func()
print('global: ', a)
local()
print('global: ', a)
global_()
print('global: ', a)

输出:

global:  in the global scope
Inside func():  in the global scope
global:  in the global scope
Inside local(): 
inside function local()
global:  in the global scope
Inside global_() : 
changed inside function global_()
global:  changed inside function global_()

非本地关键词

在Python中,嵌套函数是用Python非本地关键字来处理的。这个关键字的作用类似于全局关键字,只是在嵌套函数的情况下,它定义了一个变量,指的是外层包围函数中分配的变量,而不是全局变量。

代码

# Python program to show how the nonlocal keyword works

print ("Using the nonlocal keyword before changing a:")

# Assigning 'a' in the global scope
a = 0

# Defining a function
def outer():

    # Giving new value to 'a' in the local scope of the 'outer' function
    # Didn't use global keyword here
    a = 3
    def inner():

        # Defining the variable scope as the local scope of the 'outer' function
        nonlocal a 

        # Changing the value of 'a' in the local scope of the 'inner' function
        a = 14

        # Printing the value of 'a' in the local scope of the 'inner' function
        print("Inside 'inner' function:- ", a)

    # Calling the inner function
    inner()

    # Priting the value of 'a' inside the function
    print("Inside the 'outer' function:- ", a)

# Calling the main function
outer()

# Printing the value of 'a' in the global scope
print("In the global scope:- ", a)

# Performing the same steps as above without using the nonlocal keyword
print ("\nNot using the nonlocal keyword before changing a:")

# Assigning 'a' in the global scope
a = 0

def outer():
    a = 3

    def inner():

        # Not using the nonlocal keyword before assigning a new value to a
        a = 14
        print("Inside 'inner' function:- ", a)

    inner()
    print("Inside the 'outer' function:- ", a)

# Calling the main function
outer()

print("In the global scope:- ", a)

输出:

Using the nonlocal keyword before changing a:
Inside 'inner' function:- 
14
Inside the 'outer' function:-  14
In the global scope:- 
0

Not using the nonlocal keyword before changing a:
Inside 'inner' function:- 
14
Inside the 'outer' function:-  3
In the global scope:- 
0

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程