摄氏与华氏转变

 1 #定义摄氏度的一个类
 2 class Celsius:
 3     def __init__(self,value = 26.0):#初始化温度为26.0
 4         self.value = float(value) #将温度转化为浮点数
 5 
 6     def __get__(self,instance,owner):#定义获取摄氏温度的方法
 7                                      #返回初始化的self.value
 8         return self.value
 9 
10     def __set__(self,instance,value):#定义设置摄氏温度的方法
11         self.value = float(value)   #返回设置后的摄氏温度
12 
13 #定义华氏度的一个类
14 class Fahrenheit:
15 
16     def __get__(self,instance,owner):
17         return instance.cel * 1.8  + 32
18 
19     def __set__(self,instance,value):
20         instance.cel = (float(value) - 32) / 1.8
21 
22 class Temperature:
23     
24     cel = Celsius()
25     fah = Fahrenheit()
26 
27 >>> temp = Temperature()
28 >>> temp.cel
29 26.0
30 >>> temp.fah
31 78.80000000000001
32 >>> temp.cel = 30
33 >>> temp.cel
34 30.0
35 >>> temp.fah
36 86.0
37 >>> temp.fah = 120
38 >>> temp.cel
39 48.888888888888886
原文地址:https://www.cnblogs.com/themost/p/6517730.html