描述符类

# 描述符就是将某种特殊类型的类的实例指派给另一个类的属性
class MyDescriptor: # 某种特殊类型的类就是下面方法中至少要实现一个
def __get__(self, instance, owner): # __get__用于访问属性,它返回属性的值
print('getting...', self, instance, owner)

def __set__(self, instance, value): # __set__赋值时被调用,不返回任何内容
print('setting...', self, instance, value)

def __delete__(self, instance): # __delete__控制删除操作,不返回任何内容
print('deleting...', self, instance)


class Test:
x = MyDescriptor() # MyDescriptor类的实例x,作为Test类的属性


test = Test()
test.x # 调用__get__方法,打印出getting... self的值,instance的值和owner的值
print(test) # 打印出<__main__.Test object at 0x00000233F57555C8>,就是instance的值
print(Test) # 打印出<class '__main__.Test'>,就是owner的值
test.x = 'X-man' # 调用__set__方法,打印出setting... self的值,instance的值和value的值,value就是X-man
del test.x # 调用__delete__方法,打印出deleting... self的值和instance的值

# 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, owner):
return self.fget(instance)

def __set__(self, instance, value):
self.fset(instance, value)

def __delete__(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 = MyProperty(getX, setX, delX)


c = C()
c.x = 'hello'
print(c.x) # c.x赋值打印hello
print(c._x) # c._x也是hello
del c.x # __delete__控制删除操作,不返回任何内容
posted @ 2020-12-15 18:14  laosun0204  阅读(115)  评论(0编辑  收藏  举报