핵심 정리
Python 디스크립터는 클래스 속성으로 배치되어 인스턴스의 속성 읽기, 쓰기, 삭제 동작에 개입하는 객체입니다. 원문은 RevealAccess 예제로 이 흐름을 보여 주지만 Python 2 시절 표기와 설명을 포함하므로, 현재 Python 3 기준의 프로토콜과 구분을 먼저 확인하는 편이 안전합니다.
- 현재 Python 공식 문서에서는 __get__(), __set__(), __delete__() 중 하나를 정의한 객체를 디스크립터로 설명합니다.
- __set__() 또는 __delete__()를 정의하면 data descriptor이고, __get__()만 정의한 경우 non-data descriptor입니다. 원문의 둘 다 있어야 data descriptor라는 문장은 이 기준에 맞게 고쳐 읽어야 합니다.
- RevealAccess 객체를 MyClass.x 같은 클래스 속성에 두면 m.x를 읽을 때 __get__()이, m.x에 값을 쓸 때 __set__()이 호출되어 로깅이나 검증 같은 추가 동작을 넣을 수 있습니다.
- 원문의 print 'Retrieving' 형태는 Python 2 문법입니다. Python 3에서 실행하려면 print('Retrieving', self.name)처럼 함수 호출 형태로 바꾸며, 일반 클래스에서 object 상속을 명시할 필요도 없습니다.
- property, 인스턴스 메서드의 바인딩, staticmethod, classmethod, super 같은 Python 기능을 이해할 때도 디스크립터 프로토콜이 핵심 배경이 됩니다.
먼저 아래 예제에서 x가 인스턴스 안의 평범한 값이 아니라 클래스에 놓인 RevealAccess 객체라는 점을 보고, 읽기와 쓰기 시 출력이 생기는 순서를 따라가면 됩니다.
이어서 볼 글
- Python class variable 개념: 클래스 변수와 인스턴스 변수 차이 - 디스크립터 객체가 클래스 속성으로 저장되고 인스턴스 접근에서 동작한다는 전제를 먼저 확인할 수 있다.
descriptor
> __get__, __set__, and __delete__. If any of those methods are defined for an object, it is said to be a descriptor.
> descriptors only work for new style objects and classes.
__get__, __set__ 둘다 가진넘을 data descriptor라고 하고,
__get__ 하나만 가진넘은 non-data descriptor라고 한다.
class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print 'Retrieving', self.name
return self.val
def __set__(self, obj, val):
print 'Updating' , self.name
self.val = val
>>> class MyClass(object):
x = RevealAccess(10, 'var "x"')
y = 5
>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> m.x = 20
Updating var "x"
>>> m.x
Retrieving var "x"
20
>>> m.y
5
위 예제보면 별것도 아니네..
그냥 클래스 멥버variable접근할때 함수불리게 해서 추가동작 할 수 있는걸로 보인다.
(decorator랑도 비슷?)
근데 여러가지 파이선 기능 구현할때 이 기능을 사용해서 구현했다는거 같다.
> Descriptors are a powerful, general purpose protocol. They are the mechanism behind properties, methods, static methods, class methods, and super(). They are used used throughout Python itself to implement the new style classes introduced in version 2.2. Descriptors simplify the underlying C-code and offer a flexible set of new tools for everyday Python programs.
'Programming' 카테고리의 다른 글
| Python super()와 MRO: 상속 호출 순서 이해하기 (0) | 2026.05.31 |
|---|---|
| Jupyter Notebook 사용법: 셀 실행, 그래프 출력, 디버깅 (0) | 2026.05.31 |
| C++ 약수 구하기 방법: 완전 탐색과 O(sqrt(N)) 최적화 (0) | 2026.05.26 |
| NumPy reshape 사용법과 NaN 검사: 배열 차원 변환과 np.isnan (0) | 2026.05.26 |
| PyTorch BCELoss 사용법: criterion, output, label로 loss 계산 (0) | 2026.05.22 |
