函數對象

函數是第一類對象,即函數能夠被當作數據處理。函數

def func():
    print('from func')


print(func)
<function func at 0x10af72f28>

1、函數對象的四大功能

1.引用code

x = 'hello nick'
y = x

f = func
print(f)
<function func at 0x10af72f28>

2.看成參數傳給一個函數對象

len(x)


def foo(m):
    m()


foo(func)
from func

3.能夠看成函數的返回值ip

def foo(x):
    return x


res = foo(func)
print(res)
res()
<function func at 0x10af72f28>
from func

4.能夠看成容器類型的元素input

l = [x]

function_list = [func]
function_list[0]()
from func

2、練習

def pay():
    print('支付1e成功')


def withdraw():
    print('提現2e成功')


dic = {
    '1': pay,
    '2': withdraw,
}
while True:
    msg = """
    '1': 支付,
    '2': 提現,
    '3': 退出,
    """
    print(msg)
    choice = input('>>: ').strip()
    if choice == '3':
        break
    elif choice in dic:
        dic[choice]()
'1': 支付,
    '2': 提現,
    '3': 退出,
    
>>: 1
支付1e成功

    '1': 支付,
    '2': 提現,
    '3': 退出,
    
>>: 2
提現2e成功

    '1': 支付,
    '2': 提現,
    '3': 退出,
    
>>: 3
相關文章
相關標籤/搜索