[Python] Callbackのような動きをするclassを作る

 Pythonならclassに__call__関数を追加するだけで関数オブジェクトっぽく扱えるようになる。

 これにより、関数に状態を持たせることが可能になる。

__call__の実装


 __call__関数を実装することで、そのクラスのオブジェクトを関数オブジェクトのように扱えるようになる。

class TextDecorator:
  def __call__(self, text: str):
    print(f"-------- {text} --------")

fn = TextDecorator()
fn("hoge")  # -------- hoge --------と出力される

応用例(高階関数、関数の状態を変える)


 通常のクラスのように__init__を使って__call__を実装したクラスを高階関数(関数を返す関数)のように扱うこともできる。以下のように引数によって挙動を変えることもできる。

 また、fn.decorate_text = …のように、関数の状態を変えることも可能だ。

class TextDecorator:
  def __init__(self, decorate_text: str):
    self.decorate_text = decorate_text

  def __call__(self, text: str):
    print(f"{self.decorate_text} {text} {self.decorate_text}")

fn = TextDecorator("*****")
fn("hoge")  # ***** hoge *****と出力される
fn.decorate_text = "....."
fn("aaa")  # ..... aaa .....と出力される

コメントを残す

メールアドレスが公開されることはありません。