python知识点@函数嵌套,内置函数nonlocal和global

本文主要内容:

一、函数的嵌套

案例1

代码的执行顺序是按从上到下执行,以下给大家列出代码的执行顺序,代码先加载函数名.函数真正调用的时候加载函数里的代码

def test1(): #1
    print("test1方法----") #6
def test2(): #2
    print("test2方法") #4
test2()#3
test1()#5
print("test1方法")#7
输出:
test2方法
test1方法----
test1方法

案例2

def test1(): #1
    print("test1方法") #4
    def test2():#5
        print("test2方法") #8
    print("****1") #6
    test2() #7
    print("****2") #9
print("***3") #2
test1()#3
print("***4") #10
#输出:
***3
test1方法
****1
test2方法
****2
***4

二、 内置函数gloabal、nonlocal

1、注意:关键字nonlocal:是python3.X中出现的,所以在python2.x中无法直接使用

2、区别:

(1)global关键字用来在函数或其它局部作用域中使用全局变量。但是如果不使用全局变量也可以不适用global关键字声明。
(2)nonlocal关键字用来在函数或其它作用域中使用外层(非全局)变量

3.具体例子:

函数gloabal的使用

a = 10
def test1():
    global  a
    print(a)
    a = 100
print(a)
test1()
print(a)
输出:
10
10
100
对于可变数据类型可以直接进⾏访问
lst = ["python", "java", "C++"]
def func():
    lst.append("C")
    print(lst)
func()
print(lst)

函数nonlocal的使用

带有nonlocal a
a = 100
def test1():
    a = 200
    def test2():
        nonlocal a
        a = 300
        print(a)
    test2()
    print(a)
test1()
#输出:
300
300
没有nonlocal a
a = 100
def test1():
    a = 200
    def test2():
        a = 300
        print(a)
    test2()
    print(a)
test1()
#输出:
300
200
posted @   进击的bug~  阅读(239)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示