0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】Callable型で実現する関数に値を事前に渡す方法

Posted at

概要

Pythonにて、関数を返す関数を利用して、関数に事前に値を渡し、その関数を引数として別の関数に渡したいシチュエーションがあったため、その方法を示します。

使いどころとしては、

  • 計算ロジックの事前カスタマイズ
  • 設定値を設定したうえでの関数の引き渡し

実装

from typing import Callable

def add_value(add_val: float) -> Callable[[float], float]:
    return lambda x: add_val + x

def calc(val: float, calc_func: Callable[[float], float]):
    return calc_func(val)

print(calc(10, add_value(5)))  # 15
print(calc(10, add_value(10)))  # 20
0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?