Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Toán tử gán inplace trong Python - iadd(), isub(), iconcat()


Tiếp tục series module operator: iadd (+=), isub (-=), iconcat (+= cho sequence).

iadd() - Cộng và gán (a += b)

import operator as op

# int (immutable) - tạo object mới
print("iadd(786, 0):", op.iadd(786, 0))  # 786

# list (mutable) - INPLACE THỰC SỰ
lst = [1, 2]
op.iadd(lst, [3, 4])
print("List sau iadd:", lst)  # [1, 2, 3, 4] - lst bị sửa đổi!

isub() - Trừ và gán (a -= b)

print("isub(57, 34):", op.isub(57, 34))  # 23

iconcat() - Nối sequence (a += b)

str1 = "tutorials"
str2 = "point"
# str immutable -> tạo string mới
result = op.iconcat(str1, str2)
print("iconcat str:", result)  # tutorialspoint

# list mutable -> inplace
lst1 = [1, 2]
lst2 = [3, 4]
op.iconcat(lst1, lst2)
print("iconcat list:", lst1)  # [1, 2, 3, 4] - lst1 bị sửa đổi!

Bảng tóm tắt

HàmToán tửMutable (list)Immutable (int, str)
iadd+=Inplace thực sựTạo object mới
isub-=Inplace thực sựTạo object mới
iconcat+=Inplace thực sự (extend)Tạo object mới

Kết luận

operator.i* hữu ích cho generic code. Với mutable (list, dict, set, custom), thao tác inplace thực sự. Với immutable, tạo object mới - biến gốc không đổi trừ khi gán lại.