Anpassa attributåtkomst

Objektorienterad programmering i Python – fortsättningskurs

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'
Objektorienterad programmering i Python – fortsättningskurs

__getattr__()

# Rest of the class definition above

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

Ett objekts namnrymd är en samling attribut kopplade till objektet

__getattr__() anropas när ett försök görs att referera till ETT ATTRIBUT utanför objektets namnrymd

  • Magisk metod, anropas inte direkt
  • Tar en name-parameter
  • Implementerar anpassad funktionalitet i stället för att utlösa ett AttributeError
Objektorienterad programmering i Python – fortsättningskurs

Hantera 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
Objektorienterad programmering i Python – fortsättningskurs

__setattr__()

__setattr__() är en magisk metod som anropas när ett (nytt eller befintligt) attribut sätts eller uppdateras

  • Inkluderar attribut som sätts via __init__()
  • Tar attributets name och value
  • Använder objektets __dict__-attribut

$$

$$

Styra ändringar av attribut, validering och transformation

# 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__ lagrar alla attribut för objektet och kan användas för att hämta och spara data

Objektorienterad programmering i Python – fortsättningskurs

Anpassa attributlagring

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!")
Objektorienterad programmering i Python – fortsättningskurs

__setattr__ i praktiken

# 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!
Objektorienterad programmering i Python – fortsättningskurs

Använda __getattr__ och __setattr__ tillsammans

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
Objektorienterad programmering i Python – fortsättningskurs

Nu kör vi en övning!

Objektorienterad programmering i Python – fortsättningskurs

Preparing Video For Download...