Skip to content

บทที่ 4.3: Encapsulation และ Properties (Access Modifiers และการใช้ @property)

เอกสารนี้อธิบายเกี่ยวกับแนวคิดการปกป้องข้อมูล (Encapsulation) การกำหนดระดับการเข้าถึงข้อมูล (Access Modifiers) และการใช้งาน @property decorator ในการสร้าง Getter, Setter และ Deleter ในภาษา Python


1. การกำหนดระดับการเข้าถึงข้อมูล (Access Modifiers)

การแคปซูล (Encapsulation) คือแนวคิดการซ่อนโครงสร้างภายในและข้อมูลของออบเจกต์ ไม่ให้ถูกแก้ไขโดยตรงจากภายนอก โดยใช้เครื่องหมาย _ (Underscore) นำหน้าชื่อ Attribute หรือ Method

1.1 ระดับการเข้าถึง 3 รูปแบบ

ระดับ รูปแบบการตั้งชื่อ ขอบเขตการเข้าถึง
Public name เข้าถึงและแก้ไขได้จากทุกที่ทั้งภายในและภายนอกคลาส
Protected _name ควรเข้าถึงเฉพาะภายในคลาสและคลาสลูก (Convention สำหรับแจ้งเตือนโปรแกรมเมอร์)
Private __name เข้าถึงได้เฉพาะภายในคลาสเท่านั้น (เกิด Name Mangling ซ่อนชื่อจริง)
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner            # Public
        self._account_type = "Saving" # Protected
        self.__balance = balance      # Private

    def get_balance(self):
        # เข้าถึง Private Attribute จากภายในคลาส
        return self.__balance

account = BankAccount("Alex", 5000)

print(account.owner)          # Output: Alex
print(account._account_type)   # Output: Saving (ทำได้ แต่ไม่แนะนำตามข้อตกลง)
# print(account.__balance)    # เกิด AttributeError ทันที

print(account.get_balance())  # Output: 5000 (เข้าถึงผ่าน Getter Method)

2. การใช้งาน @property Decorator

การใช้ @property ช่วยให้สามารถเข้าถึงและแก้ไขข้อมูล Private Attribute ผ่าน Getter และ Setter ในรูปแบบเหมือนการอ่านหรือกำหนดค่าตัวแปรปกติ พร้อมใส่ Logic ตรวจสอบความถูกต้องของข้อมูลได้

2.1 การสร้าง Getter และ Setter

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.__salary = salary

    # Getter: อ่านค่า __salary
    @property
    def salary(self):
        return self.__salary

    # Setter: กำหนดค่า __salary พร้อมตรวจสอบข้อมูล
    @salary.setter
    def salary(self, value):
        if value < 15000:
            raise ValueError("เงินเดือนต้องไม่ต่ำกว่า 15,000 บาท")
        self.__salary = value

emp = Employee("Sarah", 20000)

# เข้าถึงเหมือนตัวแปรปกติ (ทำงานผ่าน @property getter)
print(emp.salary)  # Output: 20000

# แก้ไขค่าเหมือนตัวแปรปกติ (ทำงานผ่าน @salary.setter)
emp.salary = 25000
print(emp.salary)  # Output: 25000

# emp.salary = 10000 # เกิด ValueError: เงินเดือนต้องไม่ต่ำกว่า 15,000 บาท

2.2 การสร้าง Deleter (@property_name.deleter)

ใช้สำหรับกำหนดพฤติกรรมเมื่อมีการใช้คำสั่ง del กับ Property นั้นๆ

class User:
    def __init__(self, email):
        self.__email = email

    @property
    def email(self):
        return self.__email

    @email.deleter
    def email(self):
        print("กำลังลบข้อมูลอีเมล...")
        del self.__email

user = User("alex@example.com")
del user.email  # Output: กำลังลบข้อมูลอีเมล...