내부 연산자 - 세트 1 세트 2
일반 운영자는 간단한 할당 작업을 수행합니다. 반면에 Inplace 연산자는 일반 연산자와 유사하게 동작합니다. 제외하고 변경 가능 및 불변 대상의 경우 다른 방식으로 작동합니다.
- 그만큼 _추가하다_ 간단한 덧셈은 두 개의 인수를 사용하여 합계를 반환하고 인수를 수정하지 않고 다른 변수에 저장합니다.
- 반면에 _iadd_ 메소드는 또한 두 개의 인수를 취하지만 그 안에 합계를 저장하여 전달된 첫 번째 인수에서 내부 변경을 수행합니다. 이 프로세스에서는 객체 돌연변이가 필요하므로 숫자 문자열 및 튜플과 같은 불변 대상 _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 : 변경 가능한 대상
목록 및 사전과 같은 변경 가능한 대상에서 Inplace 연산자의 동작은 일반 연산자와 다릅니다. 그만큼 업데이트와 할당이 모두 수행됩니다. 변경 가능한 대상의 경우.
# 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]