zoukankan      html  css  js  c++  java
  • Python函数对象、函数嵌套和闭包函数

    函数对象:

      函数对象指的是函数可以被当做’数据’来处理,可以被引用、可以作为一个容器对象的元素、可以作为函数的参数,甚至可以是一个函数的返回值。具体使用如下案例:

    1、可以赋值

    def func():
        print("hahhahah")
    f=func              #f就是func函数的内存地址
    print(f,func)
    f()

    2、可以当做参数传给另外一个函数

    def func():
        print('from func')
        
    def foo(x): # x = func的内存地址
        # print(x)
        x()
    
    foo(func) # foo(func的内存地址)

     3、可以当做另外一个函数的返回值

    def func():
        print('from func')
    
    def foo(x): # x=func的内存地址
        return x # return func的内存地址
    
    res=foo(func) # foo(func的内存地址)
    print(res) # res=func的内存地址
    
    res()

    4、可以当做容器类型的一个元素

    def func():
        print('from func')
        
    #通过列表
    l=[func,]
    # print(l)
    l[0]()
    
    #通过字典
    dic={'k1':func}
    print(dic)
    dic['k1']()

    函数对象应用示例:

    def login():
        print('登录功能')
    
    def transfer():
        print('转账功能')
    
    def check_banlance():
        print('查询余额')
    
    def withdraw():
        print('提现')
    
    
    def register():
        print('注册')
    
    func_dic={
        "0":["退出",None],
        '1':["登录",login],
        '2':["转账",transfer],
        '3':["查询余额",check_banlance],
        '4':["提现",withdraw],
        '5':["注册",register]
    }
    
    while True:
        for i in func_dic:
            print(i,func_dic[i][0])
        choice = input('请输入命令编号:').strip()
        if not choice.isdigit():
            print('必须输入编号,傻叉')
            continue
    
        if choice == '0':
            break
    
        if choice in func_dic:
            func_dic[choice]()
        else:
            print('输入的指令不存在')

    函数嵌套:

     1、函数的嵌套调用:在调用一个函数的过程中又调用其他函数

    def max2(x,y):
        if x > y:
            return x
        else:
            return y
    
    
    def max4(a,b,c,d):
        # 第一步:比较a,b得到res1
        res1=max2(a,b)
        # 第二步:比较res1,c得到res2
        res2=max2(res1,c)
        # 第三步:比较res2,d得到res3
        res3=max2(res2,d)
        return res3
    
    res=max4(1,2,3,4)
    print(res)   #==》4

    2、函数的嵌套定义:在函数内定义其他函数

    from math import pi
    
    def circle(radius,action=0):
        """
          action参数:(0,1)
                 0 -->求圆的周长 2*pi*radius
                 1 -->求圆的面积 pi*(radius**2)
        """
        def perimeter():return 2*pi*radius
        def area():return pi*(radius**2)
    
        if action == 0:
            res = perimeter()
        else:res = area()
        return res
    print('半径为4的圆的周长为:'circle(4))
    print('半径为6的圆的面积为:'.circle(6,action=1))

    闭包函数:

    一、大前提

    # 闭包函数=名称空间与作用域+函数嵌套+函数对象
    # 核心点:名字的查找关系是以函数定义阶段为准

    二、什么是闭包函数

    # "闭"函数指的该函数是内嵌函数
    # "包"函数指的该函数包含对外层函数作用域名称的引用(不是对全局作用域

    闭包函数的使用:

    闭包函数:名称空间与作用域的应用+函数嵌套

    def f1():
        x = 33333333333333333333
        def f2():
            print(x)
        f2()
    
    
    x=11111
    def bar():
        x=444444
        f1()
    
    def foo():
        x=2222
        bar()
    
    foo()     #===>33333333333333333333

    闭包函数:名称空间与作用域的应用+函数嵌套+函数对象

    def f1():
        x = 33333333333333333333
        def f2():
            print('函数f2:',x)
        return f2
    
    f=f1()
    
    def foo():
        x=5555
        f()
    
    foo()      #===>函数f2: 33333333333333333333

    三:为何要有闭包函数=》闭包函数的应用

    # 两种为函数体传参的方式
    # 方式一:直接把函数体需要的参数定义成形参
    def f2(x):
        print(x)
    
    f2(1)
    f2(2)
    f2(3)
    
    # 方式二:通过闭包函数
    def f1(x): # x=3
        x=3
        def f2():
            print(x)
        return f2
    
    x=f1(3)
    print(x)
    
    x()

    示例:

    import requests
    
    # 传参的方案一:
    # def get(url):
    #     response=requests.get(url)
    #     print(len(response.text))
    #
    # get('https://www.baidu.com')
    # get('https://www.cnblogs.com/linhaifeng')
    # get('https://zhuanlan.zhihu.com/p/109056932')
    
    
    # 传参的方案二:
    def outter(url):
        # url='https://www.baidu.com'
        def get():
            response=requests.get(url)
            print(len(response.text))
        return get
    
    baidu=outter('https://www.baidu.com')
    baidu()
    
    cnblogs=outter('https://www.cnblogs.com/linhaifeng')
    cnblogs()
    
    zhihu=outter('https://zhuanlan.zhihu.com/p/109056932')
    zhihu()
  • 相关阅读:
    【剑指Offer】面试题14- I. 剪绳子
    【剑指Offer】面试题56
    【LeetCode】202. 快乐数
    【LeetCode】1095. 山脉数组中查找目标值
    【LeetCode】260. 只出现一次的数字 III
    【剑指Offer】面试题56
    【LeetCode】33. 搜索旋转排序数组
    【LeetCode】23. 合并K个排序链表
    【LeetCode】46. 全排列
    mysql可视化工具下载地址2017.6.27
  • 原文地址:https://www.cnblogs.com/baicai37/p/12533292.html
Copyright © 2011-2022 走看看