简单不可变对象工厂

immutable的Python项目详细描述


这个包是一个namedtuple来自collections包。

它允许您通过tuple或通过kwargs实例化。它 简化了提前知道 Immutable应该是,您只需要实例化它一次。

安装

pip install immutable

详细信息

namedtuple

namedtuple是一个pythonbuiltin,它允许您 将对象实例化如下:

fromcollectionsimportnamedtupleTupleFactory=namedtuple('ATuple',['using','these','attrs'])ATuple=TupleFactory('first',these='second',attrs='third')ATuple# ATuple(using='first', these='second', attrs='third')# dot-access attributesATuple.using# 'first'Atuple.these# 'second'ATuple.attrs# 'third'# index-access attributesATuple[0]# 'first'ATuple[1]# 'second'ATuple[2]# 'third'ATuple[-1]# 'third'# the class name is as specified in creating the original factoryATuple.__class__.__name__# 'ATuple'

ImmutableFactory

复制namedtuple功能

immutablefactory只是一个很薄的包装器,它允许您这样做 一步到位:

fromimmutableimportImmutableFactoryattributes=(('using','first'),('these','second'),('attrs','third'))# don't worry about the extra kwargs for now :)ATuple=ImmutableFactory.create(attributes,keys=False,values=False,items=False)ATuple# Immutable(using='first', these='second', attrs='third')# dot-access attributesATuple.using# 'first'Atuple.these# 'second'ATuple.attrs# 'third'# index-access attributesATuple[0]# 'first'ATuple[1]# 'second'ATuple[2]# 'third'ATuple[-1]# 'third'# the class name is *always* `Immutable` nowATuple.__class__.__name__# 'Immutable'

一些额外的铃声和口哨声(不要太激动)

大多数时候,我们并不关心订单。这样我们就可以 以much更干净的方式实例化:

fromimmutableimportImmutableFactoryATuple=ImmutableFactory.create(using='first',these='second',attrs='third',keys=False,values=False,items=False)# note that there's no predictable order hereATuple# Immutable(these='second', using='first', attrs='third')# dot-access attributesATuple.using# 'first'Atuple.these# 'second'ATuple.attrs# 'third'# doesn't really make sense to index-access attributes now, so don't.# the class name is *always* `Immutable` nowATuple.__class__.__name__# 'Immutable'

另外,像keysvalues这样的dict有助于 items。这些

注释

注意,如果使用mutable作为 Immutable对象,您可以更改它。如果这不是 在这种情况下,ImmutableFactory需要改变您的输入数据–而不是 很好。

fromimmutableimportImmutableFactoryATuple=ImmutableFactory.create(mutable=['a','list'])ATuple.mutable# ['a', 'list']ATuple.mutable.append('can change!')ATuple.mutable# ['a', 'list', 'can change!']

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

推荐PyPI第三方库


热门话题
ssl证书javax。网ssl。SSLHandshakeException:java。安全cert.CertificateException:没有与IP地址匹配的主题替代名称   基于组件的体系结构的java粒度   java在读取文件中的下一行和上一行时,我得到一个空指针异常   java是什么。StrutConfig。xml。strutsdia文件?   java中如何根据枚举字段对一组对象进行排序   java Firebase setPersistenceEnabled。导致大量内存使用   java奇数编译泛型类和列表错误   java类型org没有可用的源代码。石英克隆表达;您是否忘记继承所需的模块?   java如何使用map计算列表中整数列表的和,并获得一个新列表,其中每个条目对应于每个计算出的和?   java二进制搜索不会结束   java跳过Jackson中的错误JSON数据   在服务层中使用依赖项注入时引发java空指针异常。DAO类bean为空   访问者模式如何解释这两个Java程序运行时间的差异?   用Java扩展日历   java调用通用静态方法