属性的属性支持

attr-propert的Python项目详细描述


属性

PypiGithubPythonVersTravis buildingCodacyCodacy coverage

属性的属性支持

安装

pip install attr_property

使用

attr_propertys

定义类 ^{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。在

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
JavaSwing:如何读取组件下面的图形信息?   JAVAutil。scanner Java scanner为什么跳过代码中的nextLine()?   html如何在jsp文件中使用内联java比较器?   编组时单个元素组的java JAXB元素包装器   java如何使SeleniumWebDriver动态选择客户端证书,而无需直观地检测弹出窗口   java定位服务。FusedLocationApi。getLastLocation(mGoogleApiClient)获取null   java如何快速创建指向Eclipse中元素的Javadoc链接?   如何使用Java语言填充MS Word模板?   java 安卓应用程序不显示来自服务器的值   java有没有办法解决这个问题:第45行第7列path$处的预期名称。客户端[0]。服务   java如何使用ASM仅从switch中删除break语句?   java LOOK else if语句:我把它放在哪里   无效的Java语句   java输出不应包含0值   java遇到意外文本时要抛出什么异常?   java如何将文本文件数组中的数字添加到2d int数组中?   java如何从列表中的对象访问属性?   对象的oop锁方法(Java)   java字符串连接concat()和+运算符的有效使用