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

การใช้ Underscore (_) ใน Python

ใน Python ใช้ underscore (_) ในหลายกรณี ทั้ง single underscore (_) และ double underscore (__)

กรณีการใช้งาน Underscore

  • เก็บค่าของ expression ล่าสุดใน interpreter
  • ละเว้นค่าที่ไม่ต้องการ (ignore values)
  • ประกาศตัวแปรหรือฟังก์ชัน (naming convention)
  • แยกหลักตัวเลข (digit separators)
  • ใช้เป็นฟังก์ชัน Internationalization (i18n) / Localization (l10n)

1. ใช้ใน Interpreter (REPL)

Python Interpreter เก็บค่า expression ล่าสุดไว้ใน _

>> 20
20
>>> _
20
>>> _ + 3
23

2. ละเว้นค่า (Ignoring Values)

x, _, y = (1, 2, 3)
# x = 1, y = 3, ค่า 2 ถูกละเว้น

# ใช้ใน loop ที่ไม่ต้องการค่า index
for _ in range(10):
    print("Hello")

# Unpacking ที่ไม่ต้องการค่าบางส่วน
first, *_, last = [1, 2, 3, 4, 5]
# first=1, last=5, _=[2,3,4]

3. Naming Conventions

single_trailing_underscore_
รูปแบบชื่อ/ความหมายใช้เมื่อไหร่
single trailing underscoreหลีกเลี่ยง keyword conflict เช่น class_, def_
_single_leading_underscoreweak internal use indicatorบ่งชี้ว่าเป็น internal use (convention only, ไม่ enforce)
__double_leading_underscorename manglingในคลาส เพื่อกันชนชื่อ attribute ระหว่าง subclass
__double_leading_and_trailing_underscore__dunder/magic methodsเมธอดพิเศษของ Python เช่น __init__, __str__

ตัวอย่าง Name Mangling

class MyClass:
    def __init__(self):
        self.__private = "hidden"
        self._internal = "internal"
        self.public = "public"

obj = MyClass()
print(obj.public)        # public
print(obj._internal)     # internal (เข้าถึงได้ แต่นิยมไม่แทะ)
# print(obj.__private)   # AttributeError!
print(obj._MyClass__private)  # hidden (name mangling)

4. แยกหลักตัวเลข (Digit Separators) - Python 3.6+

dec_base = 1_000_000
print(dec_base)  # 1000000

hex_val = 0xFF_FF_FF
bin_val = 0b1010_0011
# อ่านง่ายขึ้นมากสำหรับตัวเลขใหญ่

5. Internationalization (i18n) / Localization (l10n)

เป็นเพียง convention ผูกฟังก์ชัน i18n/l10n ไว้ที่ตัวแปร _ มาจาก convention ของ C (gettext)

import gettext
_ = gettext.gettext

print(_("Hello World"))  # จะแปลตาม locale ที่ตั้งค่า

สรุป: Underscore ใน Python มีความหมายหลากหลาย ตั้งแต่ syntax feature จริง (interpreter, unpacking, digit separator) ไปจนถึง naming convention ที่ช่วยให้โค้ดอ่านง่ายและหลีกเลี่ยงข้อขัดแย้ง