파이썬에서 Descriptor는 속성 접근을 제어하는 강력한 도구입니다.
이를 통해 속성 조회(__get__), 변경(__set__), 삭제(__delete__) 동작을 원하는 방식으로 정의할 수 있습니다.
아래에서는 두 가지 예제를 통해 Descriptor의 활용 방법을 살펴보겠습니다.
1. 디렉토리 내 파일 개수 확인
import os
class DirectoryFileCount:
def __get__(self, obj, objtype=None):
return len(os.listdir(obj.dirname))
class DirectoryPath:
size = DirectoryFileCount()
def __init__(self, dirname):
self.dirname = dirname
# 현재 경로
s = DirectoryPath('./')
print(s.size)
# 이전 경로
g = DirectoryPath('../')
print(g.size)
위 코드에서 DirectoryFileCount 클래스는 디스크립터로 동작하며,
__get__ 메서드를 통해 지정된 디렉토리의 파일 개수를 반환합니다.
- s.size → 현재 디렉토리(./)의 파일 개수
- g.size → 상위 디렉토리(../)의 파일 개수
이를 통해 속성 접근만으로도 디렉토리 상태를 즉시 확인할 수 있습니다
2. 속성 접근 기록 남기기
import logging
logging.basicConfig(
format='%(asctime)s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
)
class LoggedScoreAccess:
def __init__(self, value=50):
self.value = value
def __get__(self, obj, objtype=None):
logging.info('Accessing %r giving %r', 'score', self.value)
return self.value
def __set__(self, obj, value):
logging.info('Update %r giving %r', 'score', value)
self.value = value
class Student:
# Descriptor instance
score = LoggedScoreAccess()
def __init__(self, name):
# Regular instance attribute
self.name = name
s1 = Student('Kim')
s2 = Student('Lee')
# 점수 확인
print(s2.score)
이를 통해 누가 속성에 접근했는지, 값이 어떻게 변경되었는지를 쉽게 추적할 수 있습니다.
정리하면
- Descriptor는 속성 접근 방식을 직접 정의할 수 있는 메커니즘이다.
- 활용 예제:
- 디렉토리/데이터베이스 상태 조회
- 속성 접근 기록 로깅
- 데이터 유효성 검사 및 권한 제어
Descriptor를 활용하면 속성 관리 로직을 일관되게 구현할 수 있으며, 유지보수성이 향상된다.
'파이썬 > 기초 프로그래밍' 카테고리의 다른 글
| 파이썬에서 모듈 전역 변수는 왜 함수 파라미터 없이도 사용할 수 있을까 (0) | 2026.02.03 |
|---|---|
| 데이터 엔지니어링에서 Enum을 활용한 ETL 파이프라인 설계 (0) | 2025.11.28 |
| 파이썬 Descriptor와 Property 비교 예제 (0) | 2025.09.15 |
| 파이썬 메타클래스로 커스텀 리스트 만들기 (0) | 2025.09.15 |
| Python type()을 이용한 동적 클래스 생성 가이드 (0) | 2025.09.15 |