I have this C code:
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)?
In Python, you can assign objects of any type to a variable; so you can just use any class, like this:
class test(object):
__slots__ = ['a', 'next']
x = test()
x.next = x
x.a = 42
Note that __slots__
is optional and should reduce memory overhead (it may also speed up attribute access). Also, you often want to create a constructor, like this:
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:
import collections
test = collections.namedtuple('test', ['a', 'next'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With