Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct python equivalent [duplicate]

Tags:

python

c

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)?

like image 433
user1790813 Avatar asked May 23 '13 19:05

user1790813


1 Answers

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'])
like image 67
phihag Avatar answered Oct 03 '22 20:10

phihag