函数对象

函数是第一类对象:指的是函数的内存地址可以像一个变量值一样使用。

def foo(): #foo=函数的内地址
    print('from foo')

可以通过变量名访问到值的内存地址。函数名也可访问到函数的内存地址

f=foo#函数的地址赋值给f
print(f)
f()#运行foo函数
2. 变量值可以当作参数传给另外一个函数
def foo(): #foo=函数的内地址
    print('from foo')
x = foo
def bar(x):
    print(x)
    x()

bar(x)
#<function foo at 0x00000000022CD1E0>
#from foo
3. 变量值可以当作函数的返回值
def foo(): 
    print('from foo')
def func(x):
    return x

f=func(foo)
print(f)
#<function foo at 0x000000000231D1E0>
4. 变量值可以当作容器类型的元素
def foo(): #foo=函数的内地址
    print('from foo')
l=[foo,]
print(l)
l[0]()
#
[<function foo at 0x000000000236D1E0>]
#from foo
dic={'1':foo}
print(dic)
dic['1']()
#{'1': <function foo at 0x000000000236D1E0>}
#from foo

实例:

def register():
    print('注册....')

def login():
    print('登录....')

def pay():
    print('支付....')

def transfer():
    print('转账....')

func_dic={
    '1':register,
    '2':login,
    '3':pay,
    '4':transfer
}

# func_dic['1']()

while True:
    print("""
    0 退出
    1 注册
    2 登录
    3 支付
    4 转账
    """)
    choice=input('请输入你的操作: ').strip()
    if choice == '0':break

    if choice not in func_dic:
        print('输错的指令不存在')
        continue

    func_dic[choice]()












原文地址:https://www.cnblogs.com/msj513/p/9707058.html