python - C struct python等价物

标签 python c

<分区>

我有这个 C 代码:

    typedef struct test * Test;

    struct test {
        void *a;
        Test next;
    };

您将如何在 Python 中实现与此等效的功能(如果可能的话)?

最佳答案

在 Python 中,您可以将任何类型的对象分配给变量;所以你可以使用任何类,像这样:

class test(object):
    __slots__ = ['a', 'next']

x = test()
x.next = x
x.a = 42

请注意 __slots__可选的并且应该减少内存开销(它也可以加速属性访问)。此外,您通常希望创建一个构造函数,如下所示:

class test(object):
    def __init__(self, a, next):
        self.a = a
        self.next = next

x = test(21, None)
assert x.a == 21

如果类可以是不可变的,您可能还想看看 namedtuple :

import collections
test = collections.namedtuple('test', ['a', 'next'])

关于python - C struct python等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16722337/

相关文章:

python - 如何在 Python 中反转字典(其值是列表)?

Python - 需要解析多个 XML 文件的所有元素。最快的解析器?

c - 数独网格生成器

c - “inline __attribute__((always_inline))” 在函数中是什么意思?

python - 如何使用 python 添加屏幕截图以吸引报告?

javascript - 保护 Webhook 免遭未经授权的请求?

python - Python 的 C 预处理器宏等效项

CRC(循环冗余校验)理解优化

c - 试图将 C 程序翻译成 x86 汇编

C中的CRC表算法,宽度限制