LoginSignup
2
3

More than 5 years have passed since last update.

簡単なクロージャの理解

Posted at

以下の関数内関数を返り値に取った関数があった場合

def outer(a):

    def inner(b):
        return a+b

    return inner

outer関数はオブジェクトを返す。

print(outer(1))
>>> <function outer.<locals>.inner at 0x00000000085340D0>

inner関数を実行するには

f = outer(1)
r = f(2)
print(r)

>>> 3

とする。
inner関数に与える初期値をいくつか変更したい場合などに使う。

・円の面積を求める場合

def circle_area_func(pi):
    def circle_area(radius):
        return pi * radius * radius

    return circle_area


cal1 = circle_area_func(3.14)
cal2 = circle_area_func(3.1415)

print(cal1(10))
print(cal2(10))

>>>314
>>>314.15

など場合分けができる。

以上

2
3
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
2
3