首页 > 编程语言 > 详细

Python 对象装饰器

时间:2020-12-08 09:47:57      阅读:31      评论:0      收藏:0      [点我收藏+]
# 利用对象装饰器和描述符组合来限定类实例属性的类型


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__)

 

Python 对象装饰器

原文:https://www.cnblogs.com/liangqingyun/p/14100270.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!