Python--28 描述符(preperty的原理)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python--28 描述符(preperty的原理)相关的知识,希望对你有一定的参考价值。
描述符
描述符就是将某种特殊类型的类实的实例指派给另一个类的属性。
特殊类型就是实现以下三个方法的一个或多个
__get__(self, instance, owener)
用于访问属性,它的返回属性的值
__set__(self, instance, value)
将在属性分配操作中调用,不返回任何内容
__delete__(self, instance)
控制删除操作,不返回任何内容
property就是一个描述符类
>>> 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(‘deleting...‘, self,instance) ... >>> class Test: ... x = MyDecriptor() ... >>> test = Test() >>> test.x getting... <__main__.MyDecriptor object at 0x7f43e3b3efd0> <__main__.Test object at 0x7f43e3b52048> <class ‘__main__.Test‘> >>> test <__main__.Test object at 0x7f43e3b52048> >>> test.x = ‘X-man‘ setting... <__main__.MyDecriptor object at 0x7f43e3b3efd0> <__main__.Test object at 0x7f43e3b52048> X-man >>> del test.x deleting... <__main__.MyDecriptor object at 0x7f43e3b3efd0> <__main__.Test object at 0x7f43e3b52048>
property的实现原理
>>> class Myproperty: ... def __init__(self,fget = None, fset = None, fdel = None): ... self.fget = fget ... self.fset = fset ... self.fdel = fdel ... def __get__(self,instance,owener): ... return self.fget(instance) ... def __set__(self,instance,value): ... self.fset(instance,value) ... def __del__(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 ... >>> c =C() >>> c.x = ‘C-man‘ >>> c.x ‘C-man‘ >>> del c.x
练习要求
先定义一个温度类,然后定义两个描述符类用于描述摄氏度和华氏度两个属性。
要求两个属性会自动转换,也就是说你可以给摄氏度这个属性赋值,然后打印的华氏度属性是自动转换后的结果
>>> 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 = 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 Temperarure: ... cel = Celsius() ... fah = Fahrenheit() ... >>> temp = Temperarure() >>> temp.cel 26.0 >>> temp.cel = 30 >>> temp.fah 86.0 >>> temp.fah =100 >>> temp.cel 37.77777777777778
以上是关于Python--28 描述符(preperty的原理)的主要内容,如果未能解决你的问题,请参考以下文章