속성 접근 사용자 정의

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  # 존재하지 않는 속성에 접근 시도
...
AttributeError: 'Student' object has no attribute 'residence_hall'
Python 중급 객체 지향 프로그래밍

__getattr__()

# Rest of the class definition above

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

객체의 네임스페이스는 그 객체에 연결된 속성들의 집합입니다.

__getattr__()는 객체의 네임스페이스에 없는 속성에 접근할 때 실행됩니다

  • 매직 메서드, 직접 호출하지 않음
  • name 매개변수를 받음
  • AttributeError 대신 사용자 정의 동작 구현
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  # 이제 residence_hall 속성을 다시 조회해 보세요
residence_hall does not exist in this object's namespace, try setting a value for 
  residence_hall first
Python 중급 객체 지향 프로그래밍

__setattr__()

__setattr__()는 (새/기존) 속성이 설정(set)되거나 업데이트될 때 실행되는 매직 메서드입니다

  • __init__()에서 설정한 속성도 포함
  • 속성 namevalue를 받음
  • 객체의 __dict__를 활용

$$

$$

속성 변경 제어, 검증, 변환 등에 사용

# 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__는 객체의 모든 속성을 저장하며, 데이터 조회·저장에 사용 가능

Python 중급 객체 지향 프로그래밍

속성 저장 사용자 정의

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!")
Python 중급 객체 지향 프로그래밍

__setattr__ 동작 예시

# 'str' 타입 값으로 속성 설정
karina.residence_hall = "Honors College South"
print(karina.residence_hall)
Setting residence_hall = Honors College South
Honors College South
# 'int' 타입 값으로 속성 설정
karina.student_id = 19301872
...
    raise Exception("Unexpected data type!")
Exception: Unexpected data type!
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
Python 중급 객체 지향 프로그래밍

Lass uns üben!

Python 중급 객체 지향 프로그래밍

Preparing Video For Download...