インプレース演算子 - セット1 セット2
通常のオペレーターは、単純な割り当てジョブを実行します。一方、インプレース演算子は通常の演算子と同様に動作します。 を除外する 可変ターゲットと不変ターゲットの場合では異なる方法で動作するということです。
- の _追加_ このメソッドは単純な加算を行い、2 つの引数を受け取り、引数を変更せずに合計を返し、それを別の変数に格納します。
- 一方で _iadd_ このメソッドも 2 つの引数を受け取りますが、その合計を格納することで、渡された 1 番目の引数をインプレースで変更します。このプロセスではオブジェクトの変更が必要になるため、数値文字列やタプルなどの不変ターゲットが必要になります。 _iadd_ メソッドを含めるべきではありません 。
ケース1 : 不変のターゲット。
数値文字列やタプルなどの不変ターゲット。インプレース演算子は通常の演算子と同じように動作します。つまり、代入のみが行われ、渡された引数は変更されません。
# Python code to demonstrate difference between # Inplace and Normal operators in Immutable Targets # importing operator to handle operator operations import operator # Initializing values x = 5 y = 6 a = 5 b = 6 # using add() to add the arguments passed z = operator.add(ab) # using iadd() to add the arguments passed p = operator.iadd(xy) # printing the modified value print ('Value after adding using normal operator : 'end='') print (z) # printing the modified value print ('Value after adding using Inplace operator : 'end='') print (p) # printing value of first argument # value is unchanged print ('Value of first argument using normal operator : 'end='') print (a) # printing value of first argument # value is unchanged print ('Value of first argument using Inplace operator : 'end='') print (x)
出力:
Value after adding using normal operator : 11 Value after adding using Inplace operator : 11 Value of first argument using normal operator : 5 Value of first argument using Inplace operator : 5
ケース2 : 可変ターゲット
リストやディクショナリなどの変更可能なターゲットにおけるインプレース演算子の動作は、通常の演算子とは異なります。の 更新と割り当ての両方が実行されます 可変ターゲットの場合。
# Python code to demonstrate difference between # Inplace and Normal operators in mutable Targets # importing operator to handle operator operations import operator # Initializing list a = [1 2 4 5] # using add() to add the arguments passed z = operator.add(a[1 2 3]) # printing the modified value print ('Value after adding using normal operator : 'end='') print (z) # printing value of first argument # value is unchanged print ('Value of first argument using normal operator : 'end='') print (a) # using iadd() to add the arguments passed # performs a+=[1 2 3] p = operator.iadd(a[1 2 3]) # printing the modified value print ('Value after adding using Inplace operator : 'end='') print (p) # printing value of first argument # value is changed print ('Value of first argument using Inplace operator : 'end='') print (a)
出力:
Value after adding using normal operator : [1 2 4 5 1 2 3] Value of first argument using normal operator : [1 2 4 5] Value after adding using Inplace operator : [1 2 4 5 1 2 3] Value of first argument using Inplace operator : [1 2 4 5 1 2 3]