描述符——类型检测,待补充……
先看代码:
1 # 描述的类 2 class Check(object): 3 def __init__(self, key, value_type): 4 self.k = key 5 self.t = value_type 6 7 def __set__(self, instance, value): 8 print('set方法...') 9 if isinstance(value, self.t): 10 instance.__dict__[self.k] = value 11 else: 12 raise TypeError('传入格式错误!') 13 14 def __get__(self, instance, owner): 15 print('get方法...') 16 return instance.__dict__[self.k] 17 18 def __delete__(self, instance, owner): 19 print('delete方法...') 20 return instance.__dict__.pop(self.k) 21 22 23 class C(object): 24 name = Check('name', str) 25 age = Check('age', int) 26 27 def __init__(self, name, age): 28 self.name = name 29 self.age = age 30 31 c1 = C('aa',12) 32 c1.name='cname' 33 print(c1.name)