티스토리 뷰

파이썬

디스크립터 [ __get__] [__set__][python]

글을 쓰는 개발자 2021. 9. 15. 14:56
반응형

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

라는 결과를 가져오게 된다.

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 29 30 31
글 보관함