티스토리 뷰
python 디스크립터에 대한 구동 원리
참고: https://stackoverflow.com/questions/3798835/understanding-get-and-set-and-python-descriptors
Understanding __get__ and __set__ and Python descriptors
I am trying to understand what Python's descriptors are and what they are useful for. I understand how they work, but here are my doubts. Consider the following code: class Celsius(object): def
stackoverflow.com
해당 자료를 조사하게 된 경위는 @property로 되어 있는 메소드에 대하여 테스트를 진행하면서 궁금하게 되었다.
일반적인 메소드에 대하여 Mocking을 했을 때
func = Mock(side_effect=Exception)
을 하게 되면 해당 테스틀 진행하면서 에러를 일으키게 된다.
그런데 @property의 경우에는 작동을 하지 않는다는 것을 알게 되었다.
그것에 대한 원인?은 '__get__' 이라는 메소드에 있었다.
class Celsius:
def __get__(self, instance, owner):
return 5 * (instance.fahrenheit - 32) / 9
def __set__(self, instance, value):
instance.fahrenheit = 32 + 9 * value / 5
class Temperature:
celsius = Celsius()
def __init__(self, initial_f):
self.fahrenheit = initial_f
t = Temperature(212)
print(t.celsius) # 100
t.celsius = 0
print(t.fahrenheit) # 32
해당 코드를 설명하자면
t.celsius
를 진행하게 되면
Celsius.__get__(t.celsius, t, Temperature)
로 진행하게 되면서 100을 리턴하게 된다.
t.celsius = 0
은
Celsius.__set__(t.celsius, t, 0)
으로 진행하면서
t.fahrenheit -> 32
라는 결과를 가져오게 된다.
'파이썬' 카테고리의 다른 글
[Python] Decorator 개념 정리 (0) | 2021.12.25 |
---|---|
[Python][Celery] 병렬작업을 진행하는 방법 (0) | 2021.12.20 |
[python] [path] [PYTHONHOME] [PYTHONPATH] 파이썬 경로 문제 해결 (0) | 2021.08.18 |
[python] assert 문 처리 (0) | 2021.08.04 |
[python] @property (0) | 2021.08.04 |
- Total
- Today
- Yesterday
- 2021 KAKAO BLIND RECRUITMENT
- django
- 카카오
- 그래프
- 면접
- setattr
- Spring
- Pattern
- Celery
- Collections
- 파이썬
- Java
- Python
- BFS
- Linux
- postgres
- PostgreSQL
- ubuntu
- docker-compose
- thread
- dockerignore
- 자바
- 프로그래머스
- headers
- env
- DRF
- 알고리즘
- Command Line
- docker
- 백준
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |