Python中存在可变的命名元组吗? [英] Existence of mutable named tuple in Python?

查看:112
本文介绍了Python中存在可变的命名元组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以修改命名元组或提供替代类,以使其适用于可变对象吗?

Can anyone amend namedtuple or provide an alternative class so that it works for mutable objects?

出于可读性的考虑,我想要类似于namedtuple这样的东西:

Primarily for readability, I would like something similar to namedtuple that does this:

from Camelot import namedgroup

Point = namedgroup('Point', ['x', 'y'])
p = Point(0, 0)
p.x = 10

>>> p
Point(x=10, y=0)

>>> p.x *= 10
Point(x=100, y=0)

必须腌制所得的对象.并且根据命名元组的特征,在表示对象时输出的顺序必须与构造对象时参数列表的顺序相匹配.

It must be possible to pickle the resulting object. And per the characteristics of named tuple, the ordering of the output when represented must match the order of the parameter list when constructing the object.

推荐答案

collections.namedtuple有一个可变的替代方法-

There is a mutable alternative to collections.namedtuple - recordclass.

它具有与namedtuple相同的API和内存占用量,并且支持分配(也应该更快).例如:

It has the same API and memory footprint as namedtuple and it supports assignments (It should be faster as well). For example:

from recordclass import recordclass

Point = recordclass('Point', 'x y')

>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
>>> print(p.x, p.y)
1 2
>>> p.x += 2; p.y += 3; print(p)
Point(x=3, y=5)

对于python 3.6及更高版本的recordclass(自0.5开始)支持typehints:

For python 3.6 and higher recordclass (since 0.5) support typehints:

from recordclass import recordclass, RecordClass

class Point(RecordClass):
   x: int
   y: int

>>> Point.__annotations__
{'x':int, 'y':int}
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
>>> print(p.x, p.y)
1 2
>>> p.x += 2; p.y += 3; print(p)
Point(x=3, y=5)

有一个更完整的示例(还包括性能比较).

There is a more complete example (it also includes performance comparisons).

由于0.9 recordclass库提供了另一个变体-recordclass.structclass工厂功能.它可以产生类,这些类的实例比基于__slots__的实例占用更少的内存.这对于具有属性值的实例非常重要,该属性值不打算具有参考周期.如果您需要创建数百万个实例,则可能有助于减少内存使用.这是一个说明性的示例

Since 0.9 recordclass library provides another variant -- recordclass.structclass factory function. It can produce classes, whose instances occupy less memory than __slots__-based instances. This is can be important for the instances with attribute values, which has not intended to have reference cycles. It may help reduce memory usage if you need to create millions of instances. Here is an illustrative example.

这篇关于Python中存在可变的命名元组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆