C struct python 等价物
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16722337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C struct python equivalent
提问by user1790813
I have this C code:
我有这个 C 代码:
typedef struct test * Test;
struct test {
void *a;
Test next;
};
How would you implement the equivalent to this in Python (if that is even possible)?
您将如何在 Python 中实现与此等效的功能(如果可能的话)?
采纳答案by phihag
In Python, you can assign objects of any type to a variable; so you can just use any class, like this:
在 Python 中,您可以将任何类型的对象分配给变量;所以你可以使用任何类,就像这样:
class test(object):
__slots__ = ['a', 'next']
x = test()
x.next = x
x.a = 42
Note that __slots__is optionaland should reduce memory overhead (it may also speed up attribute access). Also, you often want to create a constructor, like this:
请注意,这__slots__是可选的,应该减少内存开销(它还可以加快属性访问速度)。此外,您经常希望创建一个构造函数,如下所示:
class test(object):
def __init__(self, a, next):
self.a = a
self.next = next
x = test(21, None)
assert x.a == 21
If the class can be immutable, you may also want to have a look at namedtuple:
如果类可以是不可变的,您可能还想看看namedtuple:
import collections
test = collections.namedtuple('test', ['a', 'next'])

