python 回呼函數,python

來源:互聯網
上載者:User

python 回呼函數,python

“回呼函數就是一個通過函數指標調用的函數。

如果你把函數的指標(地址)作為參數傳遞給另一個函數,當這個指標被用來調用其所指向的函數時,我們就說這是回呼函數。”

——網上摘來的一段回呼函數的解釋,好吧,比較拗口。

我們來打個比方:

學校要進行出入管制了,告訴門衛發現寵物和車要上報(這個是回呼函數註冊),然後管理員根據門衛的上報進行處理(這個是回呼函數的執行)。

import os,sys

Find={
'Type':'',
'Color':'',
'Size':''
}#定義彙報內容

def CallFun(cmd,Find):#回呼函數的定義,在這裡處理各種回調情況
if cmd=='Type':
if Find['Type']=='Dog' or Find['Type']=='Cat':
print 'A Pet:'
else:
print 'A Transport:'
elif cmd=='Print':
print Find
else:
print 'error'

def GiveInfo(i):#該段是填報資訊,可忽略
type0=['Dog','Cat']
type1=['Car','Truck']
color0=['Black','White','Pink']
size0=['Big','Middle','Small']
t0=i % 2
if t0== 0:
Find['Type'] = type0[i%2]
else:
Find['Type'] = type1[i%2]
Find['Color'] = color0[i%3]
Find['Size'] = size0[i%3]

def FindObj(num,cmd,CallBackFun):#發現目標,啟動回呼函數
GiveInfo(num)#門衛填報資訊
CallBackFun(cmd,Find)#啟動回呼函數

if __name__ == '__main__':
cmds=['Type','Print','Try']
for i in range(0,10):#定義十次上報
print '----------%d-------------'%i
FindObj(i,cmds[i%3],CallFun)#這裡註冊回呼函數(就是告知門衛的過程)

回調利於模組解耦。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.