属性变量的集合

more-properties的Python项目详细描述


more_properties

property变体的集合。

基本用途

变体的行为基本上是内置的property,除非另有说明。

考虑到以下类别

frommore_propertiesimportproperty,class_property,static_propertyclassParrot:@propertydefname(self):return"Fred"@class_propertydeforder(cls):returnPsittaciformes@static_propertydefplanet():returnEarth

属性的访问方式如下:

^{pr2}$

设置者/删除者

setter和deleter的定义方式与内置的property相同。 或者使用decorator方法

frommore_propertiesimportclass_propertyclassFoo:name="Foo"@class_propertydefidentifier(cls):"""Object identifier"""returncls.name.lower()@identifier.setterdefidentifier(cls,value):cls.name=value.title()@identifier.deleterdefidentifier(cls):cls.name=None

或者内联方法

frommore_propertiesimportclass_propertyclassFoo:name="Foo"@classmethoddefget_identifier(cls):returncls.name.lower()@classmethoddefset_identifier(cls,value):cls.name=value.title()@classmethoddefdel_identifier(cls):cls.name=Noneidentifier=class_property(get_identifier,set_identifier,del_identifier,"Object identifier")

参考文献

property

内置^{}的修改版本。

总是表现得像个 data descriptor, 不管设置了哪个getter、setter和deleter。

在类上访问时的行为是未定义的。

class_property

类的propertycls.x和{}都使用类调用getter。 设置instance.x调用具有类和值的setter。 删除instance.x只使用类调用删除器。

frommore_propertiesimportclass_propertyclassFoo:@class_propertydefidentifier(cls):"""Class identifier"""returncls.__name__.lower()classBar(Foo):pass
>>> Foo.identifier'foo'>>> Foo().identifier'foo'
>>> Bar.identifier'bar'>>> Bar().identifier'bar'

classproperty作为同义词提供,以与classmethod保持一致。

static_property

独立于其访问器的propertycls.x和{}都不带参数地调用getter。 设置instance.x只使用值调用setter。 删除instance.x不带参数调用删除器。

frommore_propertiesimportstatic_propertyx="bar"classFoo:@static_propertydefval():returnx
>>> Foo.val'bar'>>> Foo().val'bar'

staticproperty作为同义词提供,以与staticmethod一致。

cached_property

cached_class_property

cached_static_property

分别是propertyclass_property和{}的变体。

它们的使用方法与原版相同, 但要缓存getter的值。

fromdataclassesimportdataclassfrommore_propertiesimportcached_property@dataclassclassFoo:x:int@cached_propertydefy(self):print("Doing work")returnself.x+1
>>> bar=Foo(1)>>> bar.yDoing work2>>> bar.y2

如果定义了setters/deleters, 然后在调用它们之前清除缓存。

此外,可以通过clear_cache方法显式清除缓存, 仅在类创建期间公开。

@dataclassclassFoo:x:int@cached_propertydefy(self):print("Doing work")returnself.x+1y_clear_cache=y.clear_cache
>>> bar=Foo(1)>>> bar.yDoing work2>>> bar.y2>>> bar.y_clear_cache()>>> bar.yDoing work2

安装

使用标准Python包管理器pip安装和更新:

pip install more_properties

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

推荐PyPI第三方库


热门话题
字典java cassandra对象映射注释   java定制Solr TokenFilter lemmatizer   字符串从Java文件中读取windows文件名   java如何在Windows上设置StanfordCorenlp服务器以返回文本   java axis2“意外的子元素值”   java使用POI HSSF获取错误   多线程Java等待计时器线程完成   java ForkJoinPool BuffereImage处理风格   从java代码运行Python脚本   java将字节[]转换为短[],使每个短元素包含13位数据   java如何为swing jframe应用程序将代码划分为类   java使用okhttp更改baseurl   java AlertDialog。建设者setView导致堆栈溢出错误   java如何在特定的radius 安卓 studio中接收地址列表?