现在的位置: 首页 > 综合 > 正文

004_016 Python 通过字典分派方法和函数

2017年12月10日 ⁄ 综合 ⁄ 共 366字 ⁄ 字号 评论关闭

代码如下:

#encoding=utf-8

print '中国'

#通过字典分派方法和函数

#一般都是用case的东西

def deal_with_a_cat( ):    
    print "meow"
    
def deal_with_a_dog( ):
    print "bark"

def deal_with_a_bear( ):
    print "bear"
   
tokenDict = {
    "cat": deal_with_a_cat,
    "dog": deal_with_a_dog,
    "bear": deal_with_a_bear,
    }

words = ["cat", "bear", "cat", "dog"]


def getfun(word):  
    return tokenDict[word]

print getfun('bear')()

print getfun('cat')()

打印结果如下:

中国
bear
None
meow
None

抱歉!评论已关闭.