Inplace Operators (augmented assignment) ทำการดำเนินการและกำหนดค่ากลับตัวแปรเดิม โดยไม่สร้างออบเจกต์ใหม่ (สำหรับ mutable types)
Inplace Operators พื้นฐาน
a = 9
a += 2
print(a) # 11
# เทียบเท่า
a = operator.iadd(a, 2)
ใช้ได้กับ mutable types (list, dict, set) และ immutable (int, str, tuple) แต่พฤติกรรมต่างกัน:
# Immutable: สร้าง object ใหม่
x = 5
x += 3 # x ชี้ไป object ใหม่
# Mutable: แก้ในตัว (บางครั้ง)
lst = [1, 2]
lst += [3, 4] # lst เหมือนเดิม แต่เพิ่มสมาชิก
# เทียบเท่า lst.extend([3,4])
Inplace Operators ทั้งหมด
| Operator | Function (operator module) | คำอธิบาย |
|---|---|---|
+= | iadd(a, b) | บวกและกำหนด |
-= | isub(a, b) | ลบและกำหนด |
*= | imul(a, b) | คูณและกำหนด |
/= | itruediv(a, b) | หารและกำหนด |
//= | ifloordiv(a, b) | หารปัดลงและกำหนด |
%= | imod(a, b) | modulo และกำหนด |
**= | ipow(a, b) | ยกกำลังและกำหนด |
@= | imatmul(a, b) | Matrix multiply และกำหนด |
&= | iand(a, b) | Bitwise AND และกำหนด |
|= | ior(a, b) | Bitwise OR และกำหนด |
^= | ixor(a, b) | Bitwise XOR และกำหนด |
>>= | irshift(a, b) | Right shift และกำหนด |
<<= | ilshift(a, b) | Left shift และกำหนด |
ตัวอย่าง operator module
import operator
print(operator.iadd(9, 18)) # 27
print(operator.isub(9, 18)) # -9
print(operator.imul(9, 18)) # 162
print(operator.itruediv(9, 18)) # 0.5
print(operator.imod(9, 18)) # 9
print(operator.iconcat("Tutorials", "Point")) # TutorialsPoint
print(operator.ipow(2, 6)) # 64
Standard Operators Mapping
Operator module map ออเปอเรเตอร์ทุกตัวเป็นฟังก์ชัน:
| Operation | Syntax | Function |
|---|---|---|
| Addition | x + y | add(x, y) |
| Concatenation | seq1 + seq2 | concat(seq1, seq2) |
| Containment | obj in seq | contains(seq, obj) |
| Division | x / y | truediv(x, y) |
| Floor Division | x // y | floordiv(x, y) |
| Bitwise And | x & y | and_(x, y) |
| Bitwise Or | x | y | or_(x, y) |
| Bitwise Xor | x ^ y | xor(x, y) |
| Bitwise Invert | ~x | invert(x) |
| Exponentiation | x ** y | pow(x, y) |
| Identity | x is y | is_(x, y) |
| Indexing | obj[k] | getitem(obj, k) |
| Modulo | a % b | mod(a, b) |
| Multiplication | x * y | mul(x, y) |
| Negation | -a | neg(a) |
| Not | not a | not_(a) |
| Positive | +a | pos(a) |
| Subtraction | a - b | sub(a, b) |
| Less Than | a < b | lt(a, b) |
| Equal | a == b | eq(a, b) |
| Not Equal | a != b | ne(a, b) |
ประโยชน์ของ operator module
- ใช้เป็น
keyในsort(),max(),min() - ใช้กับ
map(),reduce(),filter() - Functional programming style
- Pickleable (ไม่เหมือน lambda)