Personalizarea accesului la atribute

Programare orientată pe obiecte intermediară în 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'
Programare orientată pe obiecte intermediară în Python

__getattr__()

# Rest of the class definition above

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

Spațiul de nume al unui obiect este o colecție de atribute asociate acelui obiect

__getattr__() este executat când se încearcă referențierea oricărui atribut din afara spațiului de nume al obiectului

  • Metodă magică, nu se apelează direct
  • Primește un parametru name
  • Implementează funcționalitate personalizată, în loc să genereze un AttributeError
Programare orientată pe obiecte intermediară în Python

Rezolvarea 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
Programare orientată pe obiecte intermediară în Python

__setattr__()

__setattr__() este o metodă magică executată când un atribut (nou sau existent) este setat sau actualizat

  • Include atributele setate prin __init__()
  • Primește name-ul atributului și value
  • Utilizează atributul __dict__ al obiectului

$$

$$

Controlul modificărilor, validare, transformare

# 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__ stochează toate atributele obiectului, poate fi utilizat pentru a recupera și stoca date

Programare orientată pe obiecte intermediară în Python

Personalizarea stocării atributelor

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!")
Programare orientată pe obiecte intermediară în Python

__setattr__ în acțiune

# 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!
Programare orientată pe obiecte intermediară în Python

Utilizarea __getattr__ și __setattr__ împreună

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
Programare orientată pe obiecte intermediară în Python

Să exersăm!

Programare orientată pe obiecte intermediară în Python

Preparing Video For Download...