Python(二十五)python的全局变量和局部变量(变量作用域)

189 阅读4分钟

所谓作用域,就是变量的有效范围,就是变量可以在哪个范围以内使用。

有些变量可以在整段代码的任意位置使用,有些变量只能在函数内部使用,有些变量只能在 for 循环内部使用。

 

变量的作用域由变量的定义位置决定,在不同位置定义的变量,它的作用域是不一样的。

 

一:局部变量

在函数内部定义的变量,它的作用域也仅限于函数内部,出了函数就不能使用了,我们将这样的变量称为局部变量
要知道,当函数被执行时,Python 会为其分配一块临时的存储空间,所有在函数内部定义的变量,都会存储在这块空间中。

而在函数执行完毕后,这块临时存储空间随即会被释放并回收,该空间中存储的变量自然也就无法再被使用。

# 局部变量演示
def localvariable():
    a = 'https://guanchao.site'
    print(a)

localvariable()
#print(a)   # 这条语句执行报错

输出:

'guanchao.site'

二:全局变量

除了在函数内部定义变量,Python 还允许在所有函数的外部定义变量,这样的变量称为全局变量。
和局部变量不同,全局变量的默认作用域是整个程序,即全局变量既可以在各个函数的外部使用,也可以在各函数内部使用。

Python的全局变量比较有意思,他有两种定义方式:

1:函数体外定义的变量

# 全局变量演示
str = 'https://guanchao.site'
def globalvariable():
    print("函数内输出",str)
globalvariable()
print("函数体外输出:",str)

输出:

函数内输出 guanchao.site

函数体外输出: guanchao.site

 

2:在函数体内定义全局变量。即使用 global 关键字对变量进行修饰后,该变量就会变为全局变量。

def globalss():
    global aaa
    aaa = 'https://guanchao.site'
    print("函数内输出",aaa)
globalss()
print("函数体外输出:",aaa)

输出:

函数内输出 guanchao.site

函数体外输出: guanchao.site

 

三:获取指定作用域范围中的变量

在一些特定场景中,我们可能需要获取某个作用域内(全局范围内或者局部范围内)所有的变量,Python提供了以下3种方式:

1:globals

globals() 函数为 Python 的内置函数,它可以返回一个包含全局范围内所有变量的字典,该字典中的每个键值对,键为变量名,值为该变量的值。

#全局变量
Pyname = "时间里的"
Pyadd = "https://guanchao.site"
def text():
    #局部变量
    Shename = "时间里的局部变量"
    Sheadd"https://guanchao.site/index.php"
print(globals())

输出:

11.png

通过调用 globals() 函数,我们可以得到一个包含所有全局变量的字典。并且,通过该字典,我们还可以访问指定变量,甚至如果需要,还可以修改它的值。例如,在上面程序的基础上,例如:

print(globals()['Pyname'])
globals()['Pyname'] = "时间里的全局变量"
print(Pyname)

输出:

时间里的

时间里的全局变量

 

2:locals

locals() 函数也是 Python 内置函数之一,通过调用该函数,我们可以得到一个包含当前作用域内所有变量的字典。这里所谓的“当前作用域”指的是,在函数内部调用 locals() 函数,会获得包含所有局部变量的字典;

而在全局范文内调用 locals() 函数,其功能和 globals() 函数相同。

#locals
Pyname = "时间里的"
Pyadd = "https://guanchao.site"
def text():
    #局部变量
    Shename = "时间里的局部变量"
    Sheadd"https://guanchao.site/index.php"
    print(locals())
text()

输出:

{'Shename': '时间里的局部变量', 'Sheadd': 'guanchao.site/index.php'}

 

Locals定义的变量是一个字典,是不可被修改的

#locals
Pyname = "时间里的"
Pyadd = "https://guanchao.site"
def text():
    #局部变量
    Shename = "时间里的局部变量"
    Sheadd"https://guanchao.site/index.php"
    print(locals())
    print(locals()['Shename'])
    locals()['Shename'] = "shell入门教程"
    print(Shename)
text()

 

3:vars

vars() 函数也是 Python 内置函数,其功能是返回一个指定 object 对象范围内所有变量组成的字典。如果不传入object 参数,vars() 和 locals() 的作用完全相同。

#全局变量
Pyname = "时间里的全局变量"
Pyadd = "https://guanchao.site"
class Demo:
    name = "时间里的局部变量"
    add = "https://guanchao.site/index.php"
print("有 object:")
print(vars(Demo))
print("无 object:")
print(vars())

输出:

有 object:
{...... , 'name': '时间里的局部变量', 'add': ' guanchao.site/index.php ', ......}
无 object:
{...... , 'Pyname': '时间里的全局变量, 'Pyadd': ' guanchao.site ', ...... }

时间里的

 

以上基本上就是 python中的全局变量与局部变量的基本实用

 

有好的建议,请在下方输入你的评论‘