LoginSignup
0
3

More than 1 year has passed since last update.

PythonでIF文から脱却してみる

Last updated at Posted at 2023-03-17

Pythonは内包表記という考え方で、IF文を書かないようにした究極な例です。

なぜかpythonにはSwitch文がありません。(※before ver.3.10)

IF文はListに代替される事例は以下。
(evalを使わないとちょっと無理かもです。)
あとはデコレータを使うぐらいです。ただラッパー関数は分かりにくい。

class proc:
    def __init__(self, num):
        self.num = num
    def p_01(self):
        print('01')
    def p_02(self):
        print('02')
    def p_03(self):
        print('03')
    def run(self):
        f = ['self.p_01()','self.p_01()','self.p_02()','self.p_03()']
        res = eval(f[self.num])
if __name__ == '__main__':
    proc(2).run()

世の中は広い、この例文にはびっくり

class proc:
    def __init__(self, num):
        self.num = num
    def p_01(self):
        print('01')
    def p_02(self):
        print('02')
    def p_03(self):
        print('03')
    def run_02(self):
        return {
            1 : self.p_01,
            1 : self.p_02,
            2 : self.p_02,
            4 : self.p_03,
            5 : self.p_03,
        }[self.num]()
if __name__ == '__main__':
    proc(2).run_02()

結論としては、IF文という思考から脱却することです。

0
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3