• Python学习心得第四周-02 函数对象和嵌套


    函数是第一类对象,意味着函数可以当作数据去使用
    def foo():
        print('from foo')
    1、可以被引用
    print(foo)
    func=foo
    print(func)
    func()
    2、可以当作参数传给另外一个函数
    def bar(x): #x=foo的内存地址
        print(x)
        x()
    
    bar(foo)
    3、可以当作函数的返回值
    def bar():
        return foo
    
    f=bar()
    # print(f is foo)
    f()
    4、可以当作容器类型的元素
    def f1():
        print('from f1')
    
    def f2():
        print('from f2')
    
    l=[f1,f2]
    print(l)
    l[1]()
    
    #------------------------------------------------
    def pay():
        print('pay function')
    
    def withdraw():
        print('withdraw function')
    
    def auth():
        print('auth function')
    
    def shopping():
        print('shopping function')
    
    def transfer():
        print('transfer function')
    
    func_dic={
        '1':pay,
        '2':withdraw,
        '3':auth,
        '4':shopping,
        '5':transfer
    }
    
    # print(func_dic)
    # func_dic['2']()
    #-------------------------------------------------
    while True:
        print("""
        0 退出
        1 支付
        2 取款
        3 认证
        4 购物
        5 转账
        """)
        choice=input('请输入您要执行的操作:').strip() #choice='123'
        if choice == '0':break
        if choice not in func_dic:
            print('输入错误的指令,请重新输入')
            continue
    
        func_dic[choice]() #
    

      

    函数的嵌套调用:在调用一个函数的时,其内部的代码又调用其他的函数
    def bar():
        print('from bar')
    
    def foo():
        print('from foo')
        bar()
    
    foo()
    
    
    def max2(x,y):
        if x > y:
            return x
        else:
            return y
    
    def max4(a,b,c,d):
        res1=max2(a,b)
        res2=max2(res1,c)
        res3=max2(res2,d)
        return res3
    
    print(max4(1,2,3,4))
    

      


    函数的嵌套定义:在一个函数的内部又定义了另外一个函数
    def f1():
        x=1
        def f2():
            print('from f2')
        # print(x)
        # print(f2)
        # f2()
    
    # f1=10
    # print(f1)
    
    f1()
    # f2()
    
    print(x)
    

      

    函数对象、函数嵌套、名称空间与作用域、装饰器

    链接:http://www.cnblogs.com/linhaifeng/articles/7532497.html








  • 相关阅读:
    程序命名标准规范(自定义与其他标准无关)
    asp.net(C#)excel导入导出类
    CSS 技巧
    sql server 更改端口之后的登入方式
    日志插件 log4net 的使用
    js动态调用方法
    mongodb
    Spring 之工具类中注入bin
    解释:什么是云计算?
    当 ADO.NET 遇上 dynamic
  • 原文地址:https://www.cnblogs.com/zhutiancheng/p/9324002.html
Copyright © 2020-2023  润新知