誰か修正できますか名前付きタプルあるいは、変更可能なオブジェクトで動作するように代替クラスを提供しますか?
主に読みやすさのために、次のような namedtuple に似たものが欲しいです:
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)
結果のオブジェクトをピクル化できる必要があります。また、名前付きタプルの特性により、出力の順序は、オブジェクトを構築するときのパラメータ リストの順序と一致する必要があります。
ベストアンサー1
変更可能な代替案がありますcollections.namedtuple
-レコードクラスPyPIからインストールできます:
pip3 install recordclass
と同じ API とメモリ フットプリントを持ちnamedtuple
、割り当てをサポートします (より高速になるはずです)。例:
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)
recordclass
(0.5 以降) タイプヒントをサポート:
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)
より完全な例(パフォーマンスの比較も含まれます)。
Recordclass
ライブラリは、別のバリアントであるファクトリ関数を提供するようになりました。これは、データクラスのような API をサポートします (、、、メソッドの代わりに、モジュール レベルの関数、recordclass.make_dataclass
があります)。update
make
replace
self._update
self._replace
self._asdict
cls._make
from recordclass import dataobject, make_dataclass
Point = make_dataclass('Point', [('x', int), ('y',int)])
Point = make_dataclass('Point', {'x':int, 'y':int})
class Point(dataobject):
x: int
y: int
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
>>> p.x = 10; p.y += 3; print(p)
Point(x=10, y=5)
recordclass
とmake_dataclass
クラスを生成することができ、そのインスタンスは ベースのインスタンスよりもメモリをあまり消費しません__slots__
。これは、参照サイクルを意図していない属性値を持つインスタンスにとって重要です。数百万のインスタンスを作成する必要がある場合、メモリ使用量を削減するのに役立ちます。以下は、例。