logo

Inplace проти стандартних операторів у Python

Оператори Inplace - Набір 1 Набір 2
Звичайні оператори виконують просту роботу з призначення. З іншого боку, оператори Inplace поводяться подібно до звичайних операторів крім що вони діють по-різному у випадку змінних і незмінних цілей. 
 

  • The _add_ метод виконує просте додавання, приймає два аргументи, повертає суму та зберігає її в іншій змінній, не змінюючи жодного з аргументів.
  • З іншого боку _iadd_ метод також приймає два аргументи, але він робить зміну на місці в першому переданому аргументі, зберігаючи в ньому суму. Оскільки в цьому процесі необхідна мутація об’єктів, незмінні цілі, такі як рядки чисел і кортежі не повинен мати метод _iadd_ .
  • Звичайний оператор add()метод реалізує ' a+b ' і зберігає результат у згаданій змінній.Inplace оператора 'iadd()'метод реалізує ' a+=b ' якщо він існує (тобто у випадку незмінних цілей він не існує) і змінює значення переданого аргументу. Але якщо не реалізовано 'a+b' .


Випадок 1 : Незмінні цілі.  
У незмінних цілях, таких як рядки чисел і кортежі. Оператори Inplace поводяться так само, як і звичайні оператори, тобто відбувається лише присвоєння, без змін переданих аргументів.
 

Python
# 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 у змінних цілях, таких як списки та словники, відрізняється від звичайних операторів. The виконується як оновлення, так і призначення у разі змінних цілей.
 

Python
# 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]


 

Створіть вікторину