close

From:

(1) http://stackoverflow.com/questions/3798835/understanding-get-and-set-and-python-descriptors

(2) https://docs.python.org/2.7/reference/datamodel.html#implementing-descriptors

--------------------------------------------------------

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:
    def __init__(self, initial_f): self.fahrenheit = initial_f
    celsius = Celsius()

t = Temperature(212)

# t.celsius wuold invoke Celsius.__get__ with self = t.celsius, instance = t, owner = Temperature
print(t.celsius) # print 100.0

# t.celsius = 0 wuold invoke Celsius.__set__ with self = t.celsius, instance = t, value = 0
t.celsius = 0
print(t.fahrenheit) # print 32.0

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Foxbrush 的頭像
    Foxbrush

    Foxbrush

    Foxbrush 發表在 痞客邦 留言(0) 人氣()