Quantcast
Channel: bitWalk's
Viewing all articles
Browse latest Browse all 804

【備忘録】Python で case 文相当の処理

$
0
0

他のプログラミング言語にあって python に無いもののひとつに switch 文があります。代替案として辞書型を使う方法が多くのサイトで紹介されていますが、switch 文でそれぞれ別のメソッドに処理を移したい時に却って使いづらいと感じ、結局、if-elif-else を使う方法を採っていました。

ところが、参考サイト [1]に別の方法が紹介されていました。例えば、変数の値 1, 2, ... に対して、メソッド method_1. method_2, ... を用意しておき、getattr を使って、文字列からメソッドオブジェクトを取得して、実行するという方法です。これは使える!と思い、以下にその部分を引用し、備忘録としました。


class Switcher(object):
def numbers_to_months(self, argument):
"""Dispatch method"""
method_name = 'month_' + str(argument)
# Get the method from 'self'. Default to a lambda.
method = getattr(self, method_name, lambda: "Invalid month")
# Call the method as we return it
return method()

def month_1(self):
return "January"

def month_2(self):
return "February"

def month_3(self):
return "March"

...

参考サイト

  1. How to implement a switch-case statement in Python - JAXenter

 

ブログランキング・にほんブログ村へにほんブログ村

Viewing all articles
Browse latest Browse all 804

Trending Articles