Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonクロージャ?


Pythonクロージャをよりよく理解するために、最初にネストされた関数とPythonクラスを理解しましょう。つまり、Pythonクロージャは、データをコードでカプセル化する関数でもあります。

Pythonの入れ子関数

別の関数内で定義された関数は、ネストされた関数と呼ばれます。ネストされた関数は、囲んでいるスコープの変数にアクセスできます。

def funcOut():
   print("This is outer function.")
   def funcIn():
      print("This function is defined inside funcOut. \nThis function(funcIn) is called\
nested function.")
   print("We can call nested function here.")
   funcIn()
print("We are in outer function.\nCalling funcOut.")
funcOut()

出力

We are in outer function.
Calling funcOut.
This is outer function.
We can call nested function here.
This function is defined inside funcOut.
This function(funcIn) is called nested function.

したがって、funcInは、funcOut内で定義されるネストされた関数です。上記の出力を見ると、関数の呼び出しシーケンスを理解できます。

funcOutからfuncInのすべての機能を取得したい場合、上記のプログラムで「return funcIn」を実行する必要がある場合があります。これは、Pythonではクロージャと呼ばれます。

つまり、クロージャは、その作成環境(スコープを囲む)を記憶する関数(オブジェクト)です。

def closureFunc(start):
   def incrementBy(inc):
      return start + inc
   return incrementBy
closure1 = closureFunc(9)
closure2 = closureFunc(90)
print ('clsure1(3) = %s' %(closure1(3)))
print ('closure2(3) = %s' %(closure2(3)))

出力

clsure1(3) = 12
closure2(3) = 93

変数closure1(関数型)をclosure1(3)で呼び出すと、12が返され、closure2(3)は93が返されます。closure1とclosure2は両方とも同じ関数incrementByを参照していますが、2つの異なる変数closure1とclosure2があります。識別子closureFuncによって結合され、異なる結果になります。

__closure__ attribute and cell objects

詳細情報を取得するには、__closure__属性とセルオブジェクトを使用できます。

def closureFunc(start):
   def incrementBy(inc):
      return start + inc
   return incrementBy

a= closureFunc(9)
b = closureFunc(90)

print ('type(a)=%s' %(type(a)))
print ('a.__closure__=%s' %(a.__closure__))
print ('type(a.__closure__[0])=%s' %(type(a.__closure__[0])))
print ('a.__closure__[0].cell_contents=%s' %(a.__closure__[0].cell_contents))

print ('type(b)=%s' %(type(b)))
print ('b.__closure__=%s' %(b.__closure__))
print ('type(b.__closure__[0])=%s' %(type(b.__closure__[0])))
print ('b.__closure__[0].cell_contents=%s' %(b.__closure__[0].cell_contents))

出力

type(a) = <class 'function'>
a.__closure__ = <cell at 0x057F8490: int object at 0x68A65770>

type(a.__closure__[0]) = <class 'cell'>
a.__closure__[0].cell_contents = 9

type(b)=<class 'function'>
b.__closure__ = <cell at 0x0580BD50: int object at 0x68A65C80>

type(b.__closure__[0]) = <class 'cell'>
b.__closure__[0].cell_contents=90

上記の出力から、オブジェクトの各セルが作成時の値を保持していることがわかります。


  1. Pythonのissubset()関数

    この記事では、Python標準ライブラリで利用可能なissubset()関数の実装と使用法について学習します。 issubset()メソッドは、セットのすべての要素が別のセットに存在する場合(引数として渡される場合)はブール値のTrueを返し、それ以外の場合はブール値のFalseを返します。 下の図では、BはAのサブセットです。AとBが同一のセットである場合、AはBの適切なサブセットであることを意味します。これは、両方のセットに同じ要素が含まれていることを意味します。 構文 <set 1>.issubset(<set 2>) 戻り値 boolean True/

  2. Intersection()関数Python

    この記事では、任意のセットで実行できるintersection()関数について学習します。数学によると、共通部分とは、2つのセットから共通の要素を見つけることを意味します。 構文 <set name>.intersection(<set a1> <set a2> ……..) 戻り値 引数として渡されるセット内の共通要素。 例 set_1 = {'t','u','t','o','r','i','a','l&