简单不可变对象工厂
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'
另外,像keys、values这样的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!']