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

Toán tử gán inplace trong Python - ixor(), iand(), ipow()


Module operator cung cấp các hàm thực hiện phép toán và gán ngay lập tức (inplace), tương đương các toán tử ^=, &=, **=. Chỉ hoạt động trên đối tượng mutable (list, dict, custom class có __ixor__...), không hoạt động trên immutable (int, str, tuple).

ixor() - XOR bitwise và gán (a ^= b)

import operator as op

# Với int (immutable) - TẠO OBJECT MỚI, không inplace thực sự
result = op.ixor(786, 12)
print("ixor(786, 12):", result)  # 798 (786 ^ 12 = 798)

# Với custom mutable object
class MutableInt:
    def __init__(self, val): self.val = val
    def __ixor__(self, other): self.val ^= other; return self

m = MutableInt(786)
op.ixor(m, 12)
print("MutableInt ixor:", m.val)  # 798

iand() - AND bitwise và gán (a &= b)

result = op.iand(57, 34)
print("iand(57, 34):", result)  # 32 (57 & 34 = 32)

ipow() - Lũy thừa và gán (a **= b)

result = op.ipow(3, 2)
print("ipow(3, 2):", result)  # 9 (3 ** 2 = 9)

Lưu ý quan trọng về Immutable

x = 10
op.iadd(x, 5)  # Tạo int mới 15, gán vào biến cục bộ của hàm
print(x)       # Vẫn là 10! (int immutable)

Kết luận

Các hàm operator.i* chủ yếu dùng cho generic programming (viết hàm nhận toán tử làm tham số). Với kiểu built-in immutable (int, str, tuple), chúng tạo object mới, không sửa đổi inplace. Chỉ có ý nghĩa inplace thực sự với đối tượng mutable tự định nghĩa __iadd__, __ixor__...