디스크립터

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

Jake Roach

Data Engineer

속성 상호작용 변경하기

class Student:
    def __init__(self, name, ssn):
        self.name = name
        self.ssn = ssn
# Create a student object, and access the "ssn" attribute
shaw = Student("Daniel Shaw", "193-80-1821")
print(shaw.ssn)

# What if the value is changed or deleted? How should this be handled?
193-80-1821
Python 중급 객체 지향 프로그래밍

@property로 디스크립터 만들기

디스크립터는 속성의 조회, 설정, 삭제 방식을 제어하는 객체입니다.

@property로 디스크립터 생성

  • "getter", "setter", "deleter"
  • 메서드 이름 == 속성 이름

다음으로도 생성 가능

  • property() 함수
  • __get__(), __set__(), __delete__()

$$

class Student:
    def __init__(self, name, ssn):
        self.name = name
        self.ssn = ssn

    @property  
    def ssn(self):
        return "XXX-XX-" + self._ssn[-4:]

    @ssn.setter  
    def ssn(self, new_ssn):
        self._ssn = new_ssn 

    @ssn.deleter
    def ssn(self):
        raise AttributeError("Can't delete SSN")
Python 중급 객체 지향 프로그래밍

@property

class Student:
    def __init__(self, name, ssn):
        self.name = name
        self.ssn = ssn  # Does not need to include an underscore

    @property  
    def ssn(self):  # This is the "getter" method
        return "XXX-XX-" + self._ssn[-4:]
  • ssn 조회 방식을 제어
  • self.ssn이 아닌 self._ssn과 상호작용
Python 중급 객체 지향 프로그래밍

@ssn.setter

class Student:
    def __init__(self, name, ssn):
        self.name = name
        self.ssn = ssn
    ...

    @ssn.setter  
    def ssn(self, new_ssn):
        if len(new_ssn) == 11:
          # Add things such as data 
          # validation, operations on
          # other attributes, etc.
          self._ssn = new_ssn

@<attribute-name>.setter

  • ssn의 "setter" 메서드
  • 데이터 품질 검증
  • 다른 속성에 대한 연산 수행

$$

$$

$$

항상 self.ssn이 아닌 self._ssn과 상호작용하세요!

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

@ssn.deleter

class Student:
    def __init__(self, name, ssn):
        self.name = name
        self.ssn = ssn

    ...

    @ssn.deleter
    def ssn(self):
        # Can perform clean up, soft delete, raise exception
        raise AttributeError("Can't delete SSN")
Python 중급 객체 지향 프로그래밍

디스크립터 실습 예시

shaw = Student("Daniel Shaw", "193-80-1821")
print(shaw.ssn)  # Access the ssn attribute
XXX-XX-1821
shaw.ssn = "821-11-9380"  # Update Shaw's social security number
print(shaw.ssn)
XXX-XX-9380
del shaw.ssn  # Attempt to delete the ssn attribute
AttributeError: Can't delete SSN
Python 중급 객체 지향 프로그래밍

연습해 봅시다!

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

Preparing Video For Download...