1.描述符作用
- 描述符的一个重要作用在于用类属性实例模仿实例属性,通过三个内置特殊功能函数
__set__()
__get__()
__delete__()
来自动获取创建的实例名和实例属性值,并用其修改类属性实例 ; - 描述符可以将属性设置和获等取辅助功能放在描述符中,从而保持主要类代码的整洁性。同时也可以通过类属性来模拟初始化过程;
- 使用描述符可以提高代码的复用性;
2.代码示例:
- 使用descriptor可以省略在初始化方法对初始属性赋值进行判断;
- std_id和score都可以使用复用描述符NonNegative(),不需要对属性赋值进行重复判断;
class NonNegative(object):
def __init__(self):
self.dict = dict()
def __set__(self, ist, value):
if value < 0:
raise Exception('the value can not be negative.')
self.dict[ist] = value
def __get__(self, ist, cls): # cls形参不能丢
return self.dict[ist]
class MathScore(object):
std_id = NonNegative()
score = NonNegative()
def __init__(self, std_id, score):
self.std_id = std_id
self.score = score
def check(self):
if self.score >= 60:
print('pass')
print('failed')