【Python】-016-函数-回调
2017-08-09 本文已影响26人
9756a8680596
-
callback
,在函数A中将另一个函数作为参数callback
,函数A中调用callback
,执行完后在返回函数A -
理解为函数中需要使用到另一个函数,执行完返回之前的函数中
-
一些例子
# coding: UTF-8 def test(callback): //将函数当做变量,函数内调用其他函数 print "Test function." callback() def testFuncList(callback): print "Test fucntion list." for func in callback: func() def cb1(): print "The CallBack One." def cb2(): print "The CallBack Two." if __name__ == "__main__": test(cb1) test(cb2) //函数名作为参数 testFuncList([cb1, cb2]) //函数名列表作为参数
-
稍微复杂的例子,需求如图
需求
-
不同顾客需要使用不同的函数,发送消息
def sendEmail(address, content): print "Send: ", content, "to: ", address def sendQQ(address, content): print "Send: ", content, "to: ", address def sendWeixin(address, content): print "Send: ", content, "to: ", address def sendSMS(address, content): print "Send: ", content, "to: ", address
-
针对不同的情况,调用不同的函数,利用字典进行封装
sendMethod = { "QQ": sendQQ, "Email": sendEmail, "WeiXin": sendWeixin, "DuanXin": sendSMS, }
-
顾客信息如下,来源于文件
QQ,73465937, Chenxiansheng WeiXin,ffaazf, Xufuren DuanXin, 1234567890, Wangxiaojie Email, 111@163.com, Zenglingdao
-
给顾客发送消息
def Info(content, customFile): f = open(customFile, "r") for line in f: nonblankline = re.sub(r'\s', '',line) wordlist = nonblankline.split(',') print wordlist if wordlist[0] in sendMethod.keys(): sendMethod[wordlist[0]](wordlist[1], content) if __name__ == "__main__": Info("Buy RED BULL at $10", "/Users/caoweiwei/Box Sync/pythonTEST/custom_info.txt")