python - 装饰器+描述符(给类添加属性且属性类型审核)
装饰器+描述符
实现给一个类添加属性且对添加的时,对属性进行类型审核:
def zsq(**kwargs): def fun(obj): for i,j in kwargs.items(): setattr(obj,i,mxf(i,j)) return obj return fun class mxf(): def __init__(self,na,ty): self.na = na self.ty = ty def __get__(self, instance, owner): return instance.ty def __set__(self, instance, value): if isinstance(value,self.ty): instance.__dict__[self.na] = value else: print("%s=%s 录入类型错误...."%(self.na,value)) @zsq(name=str,old=int) class Student(): def __init__(self,name,old): self.name = name self.old = old A1 = Student('anec',18) A2 = Student(4343,'123') print(A1.__dict__) print(A2.__dict__)
既要脚踏实地,也需仰望天空