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

Getters/Setters Methods สำหรับ Python Class คืออะไร?

Getters และ Setters ใช้ในหลาย Object-Oriented Programming Languages เพื่อให้แน่ใจถึง Principle ของ Data Encapsulation พวกเขายังเรียกว่า Mutator Methods Data Encapsulation มองว่าเป็นการ Bundle Data กับ Methods ที่ Operate บน Data เหล่านั้น Methods เหล่านี้คือ Getter สำหรับ Retrieve Data และ Setter สำหรับ Change Data ตาม Principle นี้ Attributes ของ Class ถูกทำให้ Private เพื่อซ่อนและปกป้องจาก Code อื่นๆ

น่าเสียดายที่เชื่อกันอย่างแพร่หลายว่า Proper Python Class ควร Encapsulate Private Attributes ด้วย Getters และ Setters การใช้ Getters และ Setters ไม่ใช่ Easy และ Elegant วิธี Pythonic คือใช้ property หรือ Class กับ property Method ที่ใช้ Get Value ตกแต่งด้วย @property Method ที่ทำหน้าที่ Setter ตกแต่งด้วย @x.setter

ตัวอย่าง

ตัวอย่างการใช้ Getters และ Setters ดังนี้

class P:
    def __init__(self, x):
        self.__set_x(x)

    def __get_x(self):
        return self.__x

    def __set_x(self, x):
        if x < 0:
            self.__x = 0
        elif x > 1000:
            self.__x = 1000
        else:
            self.__x = x

    x = property(__get_x, __set_x)