1. **描述符就是将某种特殊类型的类的实例指派给另一个类的属性**<br />**___get__(self, instance, owner)用于访问属性,它返回属性的值**

set(self, instance, value)将在属性分配操作中调用, 不返回任何内容

delete(self, instance)控制删除,不返回任何内容

自带的 Property

  1. class MyDecriptor:
  2. def __get__(self, instance, owner):
  3. print("getting...", instance, owner)
  4. def __set__(self, instance, value):
  5. print("setting...", instance, value)
  6. def __delete__(self, instance):
  7. print("deleteting...", instance)
  8. class Test:
  9. x = MyDecriptor()
  10. test = Test()
  11. test.x
  12. test.x = "100"
  13. del test.x
  14. --------------------------------
  15. getting... <__main__.Test object at 0x0316B040> <class '__main__.Test'>
  16. setting... <__main__.Test object at 0x0316B040> 100
  17. deleteting... <__main__.Test object at 0x0316B040>

自已实现 Property

  1. class MyProperty:
  2. def __init__(self, fget = None, fset = None, fdel = None):
  3. self.fget = fget
  4. self.fset = fset
  5. self.fdel = fdel
  6. def __get__(self, instance, owner):
  7. return self.fget(instance) # instance 实例对象
  8. def __set__(self, instance, value):
  9. return self.fset(instance, value)
  10. def __delete__(self, instance):
  11. return self.fdel(instance)
  12. class Test:
  13. def __init__(self):
  14. self._x = None
  15. def getX(self):
  16. return self._x
  17. def setX(self, value):
  18. self._x = value
  19. def delX(self):
  20. del self._x
  21. x = MyProperty(getX, setX, delX)
  22. test = Test()
  23. test.x = "x-main"
  24. print(test.x) # 用x 取修改了 _x 的值 _x 属于另一个的的属性
  25. print(test._x)
  26. ------------------------------------
  27. x-main
  28. x-main

练习要求

先定义一个温度类, 然后定义两个描述符类 用于描述摄氏度和华氏度两个属性 .

要求两个属性会自动进行转换, 也就是说你可以给摄氏度这个属性赋值, 然后打印的华氏度属性是自动转换后的结果

公式: * 1.8 + 32

  1. class Celsius:
  2. def __init__(self, value = 26.0):
  3. self.value = float(value)
  4. def __get__(self, instance, owner):
  5. return self.value
  6. def __set__(self, instance, value):
  7. self.value = float(value)
  8. class Fahrenheit:
  9. def __get__(self, instance, owner):
  10. return instance.cel *1.8+32
  11. def __set__(self, instance, value):
  12. instance.cel = (float(value) - 32) / 1.8
  13. class Temperature:
  14. cel = Celsius()
  15. fah = Fahrenheit()
  16. temp = Temperature()
  17. print(temp.cel) # 默认是摄氏度
  18. temp.cel = 30 # 修改摄氏度
  19. print(temp.fah) # 自动转换为华氏度
  20. temp.fah = 100 # 输入华氏度
  21. print(temp.cel) # 自动转换摄氏度
  22. -------------------------------
  23. 26.0
  24. 86.0
  25. 37.77777777777778