การปรับแต่งการเข้าถึง Attribute

Object-Oriented Programming ใน Python ระดับกลาง

Jake Roach

Data Engineer

AttributeError

class Student:
  def __init__(self, student_name, major):
    self.student_name = student_name
    self.major = major
...
karina = Student("Karina", "Literature")
student.residence_hall  # Attempt to access an attribute that does not exist
...
AttributeError: 'Student' object has no attribute 'residence_hall'
Object-Oriented Programming ใน Python ระดับกลาง

__getattr__()

# Rest of the class definition above

  def __getattr__(self, name):
    # Implement logic here
    ...

namespace ของออบเจกต์คือกลุ่มของ attribute ที่เชื่อมโยงกับออบเจกต์นั้น

__getattr__() จะถูกเรียกใช้เมื่อมีการอ้างอิง attribute ใดก็ตามที่อยู่นอก namespace ของออบเจกต์

  • Magic method ไม่ถูกเรียกโดยตรง
  • รับพารามิเตอร์ name
  • กำหนดฟังก์ชันการทำงานเอง แทนที่จะ raise AttributeError
Object-Oriented Programming ใน Python ระดับกลาง

การแก้ไข AttributeError

class Student:
  def __init__(self, student_name, major):
    self.student_name = student_name
    self.major = major

  def __getattr__(self, name):
      print(f"""{name} does not exist in this object's namespace, try setting 
            a value for {name} first""")
karina.residence_hall  # Now, try to retrieve the residence_hall attribute again
residence_hall does not exist in this object's namespace, try setting a value for 
  residence_hall first
Object-Oriented Programming ใน Python ระดับกลาง

__setattr__()

__setattr__() คือ magic method ที่ถูกเรียกใช้เมื่อมีการ กำหนด หรือ อัปเดต attribute (ทั้งใหม่และที่มีอยู่แล้ว)

  • รวม attribute ที่กำหนดใน __init__()
  • รับ name ของ attribute และ value
  • ใช้ __dict__ attribute ของออบเจกต์

$$

$$

ควบคุมการเปลี่ยนแปลง attribute, การตรวจสอบ, และการแปลงข้อมูล

# Rest of the class definition above

  def __setattr__(self, name, value):
    # Implement logic here
    ...

    # Use __dict__ to create/update 
    # the attribute
    self.__dict__[name] = value

__dict__ เก็บ attribute ทั้งหมดของออบเจกต์ ใช้ดึงและบันทึกข้อมูลได้

Object-Oriented Programming ใน Python ระดับกลาง

การปรับแต่งการจัดเก็บ attribute

class Student:
  def __init__(self, student_name, major):
    self.student_name = student_name
    self.major = major

  def __setattr__(self, name, value):
    # If value is a string, set the attribute using the __dict__ attribute
    if isinstance(value, str):
      print(f"Setting {name} = {value}")
      self.__dict__[name] = value

    else: # Otherwise, raise an exception noting an incorrect data type
        raise Exception("Unexpected data type!")
Object-Oriented Programming ใน Python ระดับกลาง

__setattr__ ในการทำงานจริง

# Set an attribute using a value of type 'str'
karina.residence_hall = "Honors College South"
print(karina.residence_hall)
Setting residence_hall = Honors College South
Honors College South
# Set an attribute using a value of type 'int'
karina.student_id = 19301872
...
    raise Exception("Unexpected data type!")
Exception: Unexpected data type!
Object-Oriented Programming ใน Python ระดับกลาง

การใช้ __getattr__ และ __setattr__ ร่วมกัน

class Student:
    ...   

    def __getattr__(self, name):
        # Set the attribute with a placeholder
        self.__setattr__(name, None)
        return None

    def __setattr__(self, name, value):
        if value is None:  # Print a message denoting a placeholder
            print(f"Setting placeholder for {name}")

        self.__dict__[name] = value  # Set the attribute
Object-Oriented Programming ใน Python ระดับกลาง

มาฝึกกันเถอะ!

Object-Oriented Programming ใน Python ระดับกลาง

Preparing Video For Download...