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?

More than 3 years have passed since last update.

【python】クロージャ[py_03_20211006]

Posted at

###はじめに
Pythonでは関数の中に関数を定義することができます。

###実行環境
pycharm 2021.2(python3.10)

###コード1
まずはクロージャの簡単な動作から。

def func():
    def inner(a):
        print('a:', a)
        print('a**2:', a ** 2)

    inner(2)

func()

表示

a: 2
a**2: 4

###コード2
関数内関数を使うことにより、関数を戻り値として返すことができるようになります。

def adder(a):
    def inner(x):
        # xは関数内関数の引数、aはadder呼び出し時の引数
        return x + a
    return inner

# クロージャを作成し、add3, add5に代入する
add3 = adder(3)
add5 = adder(5)

# add3, add5に代入されたクロージャを呼び出す
print(add3(10))
print(add5(10))

表示

13
15
0
0
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
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?