实例
class Celsius(object):
def __init__(self, value = 26.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
print "value:",value
self.value = float(value)
class Fahrenheit(object):
def __get__(self, instance, owner):
return instance.cel * 1.8 + 32
def __set__(self, instance, value):
instance.cel = (float(value) - 32) / 1.8
class Temperature(object):
cel = Celsius()
fah = Fahrenheit()
运行结果
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
============ RESTART: C:\Users\CuiJianping\Desktop\temprature.py ============
>>> temp = Temperature()
>>> temp.cel
26.0
>>> temp.fah
78.80000000000001
>>> temp.cel = 40
value: 40
>>> temp.fah
104.0
>>> temp.fah = 100
value: 37.7777777778
>>> temp.cel
37.77777777777778