namedutils
-轻型集装箱¶
这个 namedutils
模块定义了两种轻量级容器类型: namedtuple
和 namedlist
。这两种类型都是内置序列类型的子类型,非常快速和高效。它们只需为自身内的特定索引添加命名的属性访问器。
这个 namedtuple
与内置的 collections.namedtuple
,具有几个增强功能,包括 __repr__
更适合传承。
这个 namedlist
是可变的对应物 namedtuple
,并且比完全成熟的要快得多,重量更轻 object
。如果要在树、图或其他可变数据结构中实现节点,请考虑这一点。如果你想要一个更瘦的方法,你可能不得不求助于C。
- boltons.namedutils.namedlist(typename, field_names, verbose=False, rename=False)[源代码]¶
返回具有命名字段的List的新子类。
>>> Point = namedlist('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with pos args or keywords >>> p[0] + p[1] # indexable like a plain list 33 >>> x, y = p # unpack like a regular list >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22)
- boltons.namedutils.namedtuple(typename, field_names, verbose=False, rename=False)[源代码]¶
返回具有命名字段的元组的新子类。
>>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with pos args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22)