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

ความหมายของ Single Underscore นำหน้าตัวแปรใน Python

Single Underscore (_)

ชื่อในคลาสที่ขึ้นต้นด้วย Underscore เดียว เป็น สัญญาณให้โปรแกรมเมอร์คนอื่น ว่าแอตทริบิวต์หรือเมธอดนี้ตั้งใจจะเป็น Private (Internal Use)

แนะนำให้ใช้ Single Underscore สำหรับ Semi-private และ Double Underscore สำหรับ Fully Private

จาก PEP-8:

_single_leading_underscore: weak "internal use" indicator. ตัวอย่าง: from M import * จะไม่ import ออบเจ็กต์ที่ชื่อขึ้นต้นด้วย underscore

ตัวอย่างเปรียบเทียบ Single vs Double Underscore

class MyClass():
    def __init__(self):
        self.__fullprivate = "World"
        self._semiprivate = "Hello"

mc = MyClass()
print(mc._semiprivate)      # Hello
print(mc.__fullprivate)     # AttributeError

ผลลัพธ์

Hello
Traceback (most recent call last):
  File "...", line 8, in <module>
    print mc.__fullprivate
AttributeError: MyClass instance has no attribute '__fullprivate'

__fullprivate ถูก Name Mangling กลายเป็น _MyClass__fullprivate จึงเข้าถึงโดยตรงไม่ได้