我有这个 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'])