我有一个经典的 Point
结构,我正在尝试创建它。
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
但是,我只需要有限的功能(通过属性名称访问)并且不需要命名元组的额外开销(例如长度、索引访问、__contains__
等)此外,我的用例还具有 Point.x
和 Point.y
的固定类型,因此可能还有依赖于静态类型保证的进一步破解。
有没有内存开销更少的东西?也许是 ctypes
或 Cython
解决方案?
最佳答案
我想,创建 Cython 扩展将是减少内存影响的最简单方法。 Cython 扩展类型的属性直接存储在对象的 C 结构中,并且属性集在编译时固定(很像 Python 的 __slots__
)。
cdef class Point:
cdef readonly double x, y # C-level attributes
def __init__(self, double x, double y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({}, {})'.format(self.x, self.y)
关于python - Python 中更节省内存的结构表示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853968/