<分区>
我有这个 C 代码:
typedef struct test * Test;
struct test {
void *a;
Test next;
};
您将如何在 Python 中实现与此等效的功能(如果可能的话)?
<分区>
我有这个 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/