描述符是将某种特殊类型的类实例指派给另一个类的属性,某种特殊类型的类就是这个类里面封装了get,set,delete这三个方法,可以将这个类指派给另一个类的某一个属性,这样就可以通过这三个方法对该属性进行操作,举例如下
1 class MyDecriptor: 2 def __set__(self,instance,value): 3 print(‘set‘) 4 def __get__(self,instance,owner): 5 print(‘get‘) 6 def __delete__(self,instance): 7 print(‘delete‘) 8 class A: 9 x=MyDecriptor() 10 a= A() 11 get 12 a.x=1 13 set 14 get 15 del a.x 16 delete
python中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 __set__(self,instance,value): 7 return self.fset(instance,value) 8 def __get__(self,instance,owner): 9 return self.fget(instance) 10 def __delete__(self,instance): 11 self.fdel(instance)
1 class C: 2 def __init__(self): 3 self._x=None 4 def __setX__(self,value): 5 self._x=value 6 def __getX__(self): 7 return self._x 8 def __delX__(self): 9 del self._x 10 x= Myproperty(__getX__,__setX__,__delX__)
1 c= C() 2 c.x=1 3 c._x 4 1 5 c.x 6 1 7 del c.x 8 c._x 9 Traceback (most recent call last): 10 File "<input>", line 1, in <module> 11 AttributeError: ‘C‘ object has no attribute ‘_x‘