Python编程 函数作用域

  • 作者简介:一名在校计算机学生、每天分享Python的学习经验、和学习笔记。 

  •  座右铭:低头赶路,敬事如仪

  • 个人主页:网络豆的主页​​​​​​

目录

 前言

一.函数

1.函数作用域介绍

2.L(local):局部作用域

3.G(global):全局变量

4.函数作用域的优先级


 前言

本章将会讲解Python编程中的 函数的作用域。

一.函数

1.函数作用域介绍

Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值
的。
变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。Python 的作用域一共有4种,
分别是:
  1.  L(local):局部作用域,即函数中定义的变量;
  2.  E(enclosing):嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作用域,但不是 全局的;
  3.  G(global):全局变量,就是模块级别定义的变量;
  4.  B(build-in):内建作用域,系统固定模块里面的变量,比如:int()等;
"""
注意:if判断,for循环是没有作用域的概念。
"""

# if True:
#     a =3
#
# print(a)
#
#
# for i in range(3):
#     print("hello")
#
# print(i)

2.L(local):局部作用域

# def test_one():
#     #局部变量,该变量的作用域在函数体内部
#     a = 5
#     print(111,a)
#
#
# print(222,a)
# test_one()

#全局变量
a =100

def test_one():
    print(f"a = {a}")   #在局部没有时,则取全局变量中找,100

def test_two():
    a = 200            #局部变量
    print(f"a = {a}")    #当局部有该变量时,则优先局部的。200

test_one()
test_two()

3.G(global):全局变量

当我们需要在函数内部直接修改全局变量时,我们可以将函数内部的局部变量通过 global 关键字声 明为全局变
#global
#全局变量
a =10

def test_one():
    print(f"a = {a}")   #10

def test_two():
    #a = 20   #初始化一个局部变量

    #局部变量 ---->全局变量
    global a
    a = a+10
    # a += 10
    print(f"a = {a}")    #当局部有该变量时,则优先局部的。200

test_one()
test_two()

4.函数作用域的优先级

# built-in   只要在Python环境中即可使用,了解即可
#int()

#global
a = 11


def outer():
    b = 5   # enclosing

    def inner():
        nonlocal b
        b = 6   #local
        print(b)

    inner()
    print(b)

outer()

 创作不易,求关注,点赞,收藏,谢谢~ 

猜你喜欢

转载自blog.csdn.net/yj11290301/article/details/128388254
今日推荐