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

ตัวแปร Public และ Private ในคลาส Python

ตัวแปร Public (Public Variables)

Python ไม่จำกัดการเข้าถึงตัวแปรหรือเรียกเมธอดใดๆ ทุกตัวแปรและเมธอดเป็น Public โดยค่าเริ่มต้น เมื่อต้องการให้เป็น Public เพียงแค่ไม่ต้องทำอะไรเพิ่มเติม

ตัวอย่าง

class Mug:
    def __init__(self):
        self.color = None
        self.content = None
    def fill(self, beverage):
        self.content = beverage
    def empty(self):
        self.content = None

brownMug = Mug()
brownMug.color = "brown"
print(brownMug.empty())
print(brownMug.fill('tea'))
print(brownMug.color)
print(brownMug.content)

ตัวแปรและเมธอดทั้งหมดเป็น Public

ตัวแปร Private (Private Variables) - Name Mangling

Python รองรับ Name Mangling ชื่อสมาชิกที่ขึ้นต้นด้วย Underscore อย่างน้อย 2 ตัว และลงท้ายด้วย Underscore สูงสุด 1 ตัว จะถูกเปลี่ยนเป็น _<ClassName><MemberName>

ตัวอย่าง

class Cup:
    def __init__(self, color):
        self.__content = None  # private variable
    def fill(self, beverage):
        self.__content = beverage
    def empty(self):
        self.__content = None

ตอนนี้ Cup สามารถเติม/เทน้ำได้ผ่าน fill() และ empty() เท่านั้น หากพยายามเข้าถึง __content จากภายนอกจะได้ Error แต่ยังสามารถเข้าถึงได้ผ่าน Name Mangling:

redCup = Cup("red")
redCup._Cup__content = "tea"  # เข้าถึงได้จริง แต่ไม่ควรทำ