python - Python 中更节省内存的结构表示?

标签 python c struct cython ctypes

我有一个经典的 Point 结构,我正在尝试创建它。

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])

但是,我只需要有限的功能(通过属性名称访问)并且不需要命名元组的额外开销(例如长度、索引访问、__contains__ 等)此外,我的用例还具有 Point.xPoint.y 的固定类型,因此可能还有依赖于静态类型保证的进一步破解。

有没有内存开销更少的东西?也许是 ctypesCython 解决方案?

最佳答案

我想,创建 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/

相关文章:

c - 如何在 C 程序中编译 Perl 代码?

c++ - 理解 "const"在声明中的位置

c - 为什么我不能从数组中删除一个人?

struct - 结构构造函数中的 f# NativePtr.stackalloc

scala - 如何将两个具有不同结构类型字段的 spark Dataframe 联合起来?

c - 程序无法正常运行

python - Heroku 的 Procfile 的正确目录

用于转换 pandas groupby 数据框的 Python lambda 函数语法

python - numpy 3D 点积

python - 在直方图中绘制 x-ticks matplotlib