function函数

 

  1. 内层函数没有引用外层函数局部变量,dir()是不会显示的
    复制代码
    def b(a):
        def p():
            print('function p dir ->',dir())
        p()
        print('function b dir ->',dir())
    b(2)
    复制代码

     

     

    复制代码
    def b(a):
        def p():
            nonlocal a
            print('function p dir ->',dir())
        p()
        print('function b dir ->',dir())
    b(2)
    复制代码

     

     

    复制代码
    def b(a):
        def p():
            print('function p dir ->',dir())
            return a
        p()
        print('function b dir ->',dir())
    b(2)
    复制代码

     

     

  2. 要想调用直接调用内层函数,必须先调用外层函数,将内层函数返回,用变量保存
    复制代码
    def b():
        def p():
            print('pppp')
        return p
    v=b()
    v()
    print(v.__name__,v)
    复制代码

     

     

    复制代码
    indicator=0
    def b():
        global indicator
        def p1():
            print('11111111')
    
        def p2():
            print('2222222222')
    
        def p3():
            print('3333333333333')
    
        def p4():
            print('4444444444444444444')
    
        if indicator==0:
            return None
        elif indicator==1:
            return p1
        elif indicator==2:
            return p2
        elif indicator==3:
            return p3
        elif indicator==4:
            return p4
        else:
            raise NotImplementedError('indicator is wrong!')
    
    v=b()
    print(v)
    indicator=1
    v1=b()
    print(v1.__name__,v1)
    indicator=2
    v2=b()
    print(v2.__name__,v2)
    复制代码

     

     

posted @   ascertain  阅读(152)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示