https://blog.csdn.net/weixin_45912307/article/details/115607332
描述器类: 一个类中,只要出现__get__
、__set__
、__delete__
中的任何一个,该类就被称为描述器类
# -- encoding: utf-8 --
# @time: 2021/4/6 23:58
# @Author: jsonLiu
# @Email: xxxxxxxx@qq.com
# @file: descriptor
class DescriptorClass(object):
def __get__(self, instance, owner):
"""
:param instance: 实例对象
:param owner:
:return:
"""
print("__get__获取属性时被触发")
return self.value
def __set__(self, instance, value):
"""
:instance: 实例对象
:param value: 值
:return:
"""
print("__set__设置属性时被触发")
self.value = value
def __delete__(self, instance):
print("__delete__删除属性时被触发")
# del self.value
self.value = None
class Model(object):
DC = DescriptorClass() # 描述器对象:会覆盖类属性(__getattr__、__setattr__、__delattr__)相关操作
def __init__(self):
super().__init__()
M = Model()
M.DC = 52.0 # M:self,DC:instance,52.0:value # __set__设置属性时被触发
print(M.DC) # __get__获取属性时被触发 52.0
del M.DC # __delete__删除属性时被触发
print(M.DC) # __get__获取属性时被触发 None