描述符就是将某种特殊类型的类的实例指派给另一个类的属性
例如下面的示例
class MyDecriptor():
def get(self,instance,owner):
print("getting...",self,instance,owner)
def __set__(self,instance,value):
print("setting...",self,instance,value)
def __delete__(self,instance):
print("delete...",self,instance)
class Test():
x = MyDecriptor()//就是把MyDecriptor的实例指派给了Test类的属性x
porperty 的原理
class MyPorperty():
def init(self,fget,fset,fdel):#fget,fset,fdel都是函数
self.fget = fget
self.fset = fset
self.fdel = fdel
def __get__(self,instance,owner):
return self.fget(instance)
def __set__(self,instance,value):
self.fset(instance,value)
def __deleted__(self,instance):
self.fdel(instance)
class C():
def init(self):
self._x = None
def getX(self):
return self._x
def setX(self,value):
self._x = value
def delX(self):
del self._x
x = MyPorperty(getX,setX,delX)//getX对应的函数是fget,setX对应的函数是fset,delX对应的函是fdel
例子 摄氏温度和华氏温度的转变
class Celsius():
def init(self,value = 26.0):
self.value = float(value)
def __get__(self,instance,owner):
return self.value
def __set__(self,instance,value):
self.value = float(value)
class Fahrenheit():
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():
cel = Celsius()
fah = Fahrenheit()