python之描述符

扫码查看

描述符是将某种特殊类型的类实例指派给另一个类的属性,某种特殊类型的类就是这个类里面封装了get,set,delete这三个方法,可以将这个类指派给另一个类的某一个属性,这样就可以通过这三个方法对该属性进行操作,举例如下

 class MyDecriptor:
def __set__(self,instance,value):
print('set')
def __get__(self,instance,owner):
print('get')
def __delete__(self,instance):
print('delete')
class A:
x=MyDecriptor()
a= A()
get
a.x=1
set
get
del a.x
delete

python中property()方法就是通过描述符的原理是实现的

 class Myproperty:
def __init__(self,fget=None,fset=None,fdel=None):
self.fget=fget
self.fset=fset
self.fdel=fdel
def __set__(self,instance,value):
return self.fset(instance,value)
def __get__(self,instance,owner):
return self.fget(instance)
def __delete__(self,instance):
self.fdel(instance)
 class C:
def __init__(self):
self._x=None
def __setX__(self,value):
self._x=value
def __getX__(self):
return self._x
def __delX__(self):
del self._x
x= Myproperty(__getX__,__setX__,__delX__)
 c= C()
c.x=1
c._x
1
c.x
1
del c.x
c._x
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'C' object has no attribute '_x'
05-11 09:34
查看更多