属性的属性支持
attr-propert的Python项目详细描述
属性
属性的属性支持
安装
pip install attr_property
使用
用attr_property
s
定义类
^{pr2}$
getter、setter和deleter规范
defa_getter(this,value):print('Property a has been accessed!')returnvalue+1defa_setter(this,value):print(f'Property a has been set with value {value!r}')defa_deleter(this):print('Property has been deleted!')@attr_property_class@attr.sclassA:a=attr_property(getter=a_getter,setter=a_setter,deleter=a_deleter)a=A(a=1)# Property a has been set with value 1# Property a has been accessed!print('a.a =',a.a)# a.a = 2dela.a# Property has been deleted!a.a# Error
禁用删除器
@attr_property_class@attr.sclassA:a=attr_property(deleter=False)a=A(1)dela.a# AttributeError: can't delete attribute
禁用setter
@attr_property_class@attr.sclassA:# remember you can set init = True or# set any default values for it,# as setter will be called in __init__# this will cause AttributeErrora=attr_property(init=False,setter=False,getter=lambdathis,value:2)a=A()a.a=1# AttributeError: can't set attribute# OK to call gettera.a==2
在setter
中运行attr.ib
的转换器和验证器
@attr_property_class@attr.sclassA:a=attr_property(converter=int,validator_runtime=True,converter_runtime=True)@a.validatordeflessthan20(self,attribute,value):ifvalue>=20:raiseValueError("d should be less than 20.")a=A('3')# a.a == 3a.a='30'# ValueError
设定器的执行顺序:
- 删除缓存值
- 运行转换器
- 运行验证程序
- 运行指定的设置程序
- 将值另存为原始值
缓存getter结果
@attr_property_class@attr.sclassA:a=attr_property(getter=lambdathis,value:value+1,cache=True)a=A(1)# a.a == 2# will not do value + again# validators and converters will be skipped, as well.
在计算getter之前访问原始值
@attr_property_class@attr.sclassA:a=attr_property(getter=lambdathis,value:value+1,convert=int,raw=True)a=A('1')# a.a == 2# a._a == 1 # converted valuea._a=9# AttributeError, it's readonly
使用不同的前缀
@attr_property_class@attr.sclassA:a=attr_property(getter=lambdathis,value:value+1,convert=int,raw='raw_')a=A('1')# a.raw_a == 1
它是如何工作的?在
- Hack attrs的
_attrs_to_init_script
函数插入代码以启动self.__attrs_property_raw__
以保存原始值,__attrs_property_cached__
以保存缓存值。在 - 为类decorator
attr_property_class
中的每个属性创建{}s。在
- 项目
标签: