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








转载于:https://www.cnblogs.com/zhutiancheng/p/9324002.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值