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

Double Underscore Prefix ทำอะไรในตัวแปร Python

Double Underscore Prefix (__)

ใน Python ใช้ Double Underscore นำหน้าชื่อแอตทริบิวต์ แอตทริบิวต์เหล่านั้นจะ เข้าถึง/มองเห็นโดยตรงจากภายนอกไม่ได้ Double Underscore จะทำ Name Mangling เปลี่ยนชื่อแอตทริบิวต์ แม้จะเข้าถึงได้ด้วยไวยากรณ์พิเศษ แต่ไม่ควรทำ

จากเอกสาร Python:

หากคลาสของคุณตั้งใจจะถูกสืบทอด และมีแอตทริบิวต์ที่ไม่อยากให้ Subclass ใช้ ให้ตั้งชื่อด้วย Double Leading Underscores และไม่มี Trailing Underscores จะเรียก Name Mangling Algorithm ชื่อคลาสจะถูกผสมเข้าไปในชื่อแอตทริบิวต์ ช่วยป้องกันการชนชื่อแอตทริบิวต์ใน Subclass

ตัวอย่าง

class MyClass:
    __hiddenVar = 0
    def add(self, increment):
        self.__hiddenVar += increment
        print(self.__hiddenVar)

myObject = MyClass()
myObject.add(3)   # 3
myObject.add(8)   # 11
print(myObject.__hiddenVar)  # AttributeError

ผลลัพธ์

3
11
Traceback (most recent call last):
  File "...", line 12, in <module>
    print (myObject.__hiddenVar)
AttributeError: MyClass instance has no attribute '__hiddenVar'

พยายามเข้าถึงจากภายนอกโดยตรงจะเกิด Exception