Pythonクックブック(4章)
条件に応じて関数呼び出し
Pythonでは、swith~caseは使えないのでif~elif~elseで条件分岐を作って、関数呼び出しが自分で考えつく方法
ディクショナリとget()を使うと、条件分岐を作らなくても実現可能。とっても見やすい。
if~elif~ 相当をやっているのが、get()でディクショナリのキーがヒットした時で、
else 相当をやっているのが、get()でキーがヒットしないとき
[kobakoba0723@fedora13-intel64 ~]$ cat func_dict.py animals = [] number_of_felines = 0 def deal_with_others(): print "No types" def deal_with_a_cat(): global number_of_felines print "meow" animals.append('feline') number_of_felines += 1 def deal_with_a_dog(): print "bark" animals.append('canine') def deal_with_a_bear(): print "watch out for the HUG" animals.append('ursine') tokenDict = { "cat": deal_with_a_cat, "dog": deal_with_a_dog, "bear": deal_with_a_bear, } words = ['cat', 'dog', 'lion', 'bear', 'snake', 'cats'] for word in words: tokenDict.get(word, deal_with_others)() nf = number_of_felines print 'we met %d felines%s' % (nf, 's'[nf == 1:]) [kobakoba0723@fedora13-intel64 ~]$ python func_dict.py meow bark No types watch out for the HUG No types No types we met 1 felines [kobakoba0723@fedora13-intel64 ~]$
getを使わずに、tokenDict[word]とやりたい場合は、
その前にキーが存在するか word in tokenDict でチェックすれば出来るが、
条件分岐が生じるので今のままの方が解りよい。
位置引数、キーワード引数の渡し方。
関数側で受け取った位置引数(*args), キーワード引数(**kwargs)をさらに別の関数に渡す時は、*args, **kwargsで渡す
[kobakoba0723@fedora13-intel64 ~]$ cat func_args.py def func(*args, **kwargs): print type(args) print type(kwargs) print "'a' in subroutine", args print "'b' in subroutine", kwargs print 'args is same as a ?', a is args print 'kwargs is same as b ?', b is kwargs a = (1, 2, 3) b = {'a': 1, 'b': 2, 'c': 3} print "'a' in main route", a print "'b' in main route", b func(*a, **b) [kobakoba0723@fedora13-intel64 ~]$ python func_args.py 'a' in main route (1, 2, 3) 'b' in main route {'a': 1, 'c': 3, 'b': 2} <type 'tuple'> <type 'dict'> 'a' in subroutine (1, 2, 3) 'b' in subroutine {'a': 1, 'c': 3, 'b': 2} args is same as a ? False kwargs is same as b ? False [kobakoba0723@fedora13-intel64 ~]$
呼び出し側と呼び出される側で、引数の参照先が共有されているかと思っていたがそうではない。
ただし、今後ずっと『共有されない』という保証はどこにもない(仕様として定義されていない)
参考サイト
キーの確認(in演算子, has_keyメソッド)@PythonWeb
始めてのPython(16章)@kobakoba0723の日記
- 作者: Alex Martelli,Anna Martelli Ravenscroft,David Ascher,鴨澤眞夫,當山仁健,吉田聡,吉宗貞紀
- 出版社/メーカー: オライリー・ジャパン
- 発売日: 2007/06/26
- メディア: 大型本
- 購入: 11人 クリック: 423回
- この商品を含むブログ (85件) を見る