Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Inplace vs Standard Operators ใน Python: +=, -=, *= และ operator module

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 ทั้งหมด

OperatorFunction (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 ออเปอเรเตอร์ทุกตัวเป็นฟังก์ชัน:

OperationSyntaxFunction
Additionx + yadd(x, y)
Concatenationseq1 + seq2concat(seq1, seq2)
Containmentobj in seqcontains(seq, obj)
Divisionx / ytruediv(x, y)
Floor Divisionx // yfloordiv(x, y)
Bitwise Andx & yand_(x, y)
Bitwise Orx | yor_(x, y)
Bitwise Xorx ^ yxor(x, y)
Bitwise Invert~xinvert(x)
Exponentiationx ** ypow(x, y)
Identityx is yis_(x, y)
Indexingobj[k]getitem(obj, k)
Moduloa % bmod(a, b)
Multiplicationx * ymul(x, y)
Negation-aneg(a)
Notnot anot_(a)
Positive+apos(a)
Subtractiona - bsub(a, b)
Less Thana < blt(a, b)
Equala == beq(a, b)
Not Equala != bne(a, b)

ประโยชน์ของ operator module

  • ใช้เป็น key ใน sort(), max(), min()
  • ใช้กับ map(), reduce(), filter()
  • Functional programming style
  • Pickleable (ไม่เหมือน lambda)