函數對象


函數是第一類對象,即函數可以被當做數據處理。

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


print(func)
<function func at 0x10af72f28>

一、函數對象的四大功能

1.引用

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.可以當作函數的返回值

def foo(x):
    return x


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

4.可以當作容器類型的元素

l = [x]

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

二、練習

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM