ITと雑記とド田舎と

ド田舎在住エンジニアがIT備忘録と雑記を書くブログです

Python3 変数に関数を代入して呼び出し

Python3 覚え書きNo.3です。

 

変数に関数を代入すればいいという発想がなかなか思いつかなかったのでメモ。

多分デコレータのこととか考えると当然のことなんだろうな。精進します。

 

class MyClass:
    def __init__(self, select_num=0):
        if select_num == 0:
            self.call_func = self.my_func1
        elif select_num == 1:
            self.call_func = self.my_func2
        elif select_num == 2:
            self.call_func = self.my_func3
        else:
            self.call_func = self.my_func1

    def my_func1(self):
        print('Hello, func1!')

    def my_func2(self):
        print('Hello, func2!')

    def my_func3(self):
        print('Hello, func3!')

    def call_my_func(self):
        print('-------------------')
        self.call_func()
        print('-------------------')


test_func = MyClass(1)
test_func.call_my_func()

実行結果
-------------------
Hello, func2!
-------------------