디스크립터 [ __get__] [__set__][python]
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
라는 결과를 가져오게 된다.