# 利用对象装饰器和描述符组合来限定类实例属性的类型
class Typed: def __init__(self,key,type): self.key=key self.type=type def __get__(self, instance, owner): print(‘__get__‘) return instance.__dict__[self.key] def __set__(self, instance, value): print(‘__set__‘) if type(value) is self.type: instance.__dict__[self.key]=value else: raise TypeError(‘属性【%s】的类型必须是%s‘%(self.key,self.type)) def __delete__(self, instance): print(‘__delete__‘) del instance.__dict__[self.key] def method(**kwargs): def wrapper(obj): for key,value in kwargs.items(): setattr(obj,key,Typed(key,value)) # 利用装饰器将描述符设置到类里面 return obj return wrapper @method(x=str,y=int) class Foo: def __init__(self,x,y): self.x=x self.y=y f=Foo(‘jack‘,23) print(f.__dict__)
原文:https://www.cnblogs.com/liangqingyun/p/14100270.html