Understanding __get__ and __set__ and Python descriptors

后端 未结 7 1413
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 06:15

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 co

7条回答
  •  我在风中等你
    2020-11-22 06:23

    I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).

    The code:

    #!/usr/bin/env python
    class Celsius:
        def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
        def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0
    
    class Temperature:
        def __init__(self, initial_f): self.fahrenheit = initial_f
        celsius = Celsius()
    
    if __name__ == "__main__":
    
        t = Temperature(212)
        print(t.celsius)
        t.celsius = 0
        print(t.fahrenheit)
    

    The result:

    C:\Users\gkuhn\Desktop>python test2.py
    <__main__.Celsius instance at 0x02E95A80>
    212
    

    With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.

提交回复
热议问题