6

python基础复习之使用字典分派函数

 2 years ago
source link: https://www.hi-roy.com/posts/python%E5%9F%BA%E7%A1%80%E5%A4%8D%E4%B9%A0%E4%B9%8B%E4%BD%BF%E7%94%A8%E5%AD%97%E5%85%B8%E5%88%86%E6%B4%BE%E5%87%BD%E6%95%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python基础复习之使用字典分派函数

2016-01-26

程序中很常见的一种场景就是根据某个控制变量的值来调用不同的函数或对象进行处理,某些语言中可以使用case语句进行处理,在python可以使用getattr函数甚至if…elif…else来处理,除此之外,也可以使用字典来实现相同的功能,比如下面的例子:

animals = []
number_of_felines = 0
def deal_cat():
    global number_of_felines
    print "meow"
    animals.append('feline')
    number_of_felines += 1
def deal_dog():
    print 'bark'
    animals.append('canine')
def deal_bear():
    print "hug"
    animals.append('ursine')
token = {'cat': deal_cat, 'dog': deal_dog, 'bear': deal_bear}
#words = ['cat', 'dog', 'bear']
words = ['cat', 'dog', 'bear', 'cat']
for one in words:
    token[one]()
    #return token[one]()
nf = number_of_felines
print 'we met %d feline%s' % (nf, 's'[nf == 1:])
print 'the animals we net were:', ' '.join(animals)

以上代码来源于《python cookbook》 第二版4.16节,原书中在for循环中使用return会报错,但本质上就是模拟根据不同的key来调用不同函数,所以去掉return即可。运行输出结果如下:

meow
bark
hug
meow
we met 2 felines
the animals we net were: feline canine ursine feline

这里解释一下's'[nf == 1:]这句话,这句话最终的目的其实就是决定feline的单复数形式罢了。从代码层面来讲,等同于:

In [23]: "abc"[False:]
Out[23]: 'abc'
In [24]: "abc"[True:]
Out[24]: 'bc'

再进一步说就是:

In [25]: "abc"[0:]
Out[25]: 'abc'
In [26]: "abc"[1:]
Out[26]: 'bc'

因为在py2.7中:

In [28]: 0 == False
Out[28]: True
In [30]: 1 == True
Out[30]: True

虽然举例的代码是函数,但把函数换成对象、类都是可以的。这里再向大家推荐一下《python cookbook》这本书,如果你和我一样已经过了入门阶段而想要有进一步提高的话,建议把这本书通读并实践,而不是遇到某个问题才去找解决方案,这本书里有很多让人眼前一亮的小技巧以及让人豁然开朗的技术解答。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK