8

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

glglgl
  • 89,107
  • 13
  • 149
  • 217
user1790813
  • 694
  • 2
  • 7
  • 22
  • 2
    @Eddy_Em What do you smoke right now? – glglgl May 23 '13 at 19:38
  • @glglgl, maybe you can tell me how can I make strict variable type in python? For example: `float a; char *b; void *f; double t;`? – Eddy_Em May 23 '13 at 19:40
  • 1
    @Eddy_Em What does this have to do with "being a real programming language"? And why shouldn't it not be possible? Look at the linked "duplicate" question or the answer below - here you see how it would work. – glglgl May 23 '13 at 19:48

1 Answers1

20

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'])
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 3
    I'm not positive that `__slots__` makes the code run any faster in general (although I suppose it might). Generally it is used to save memory if you're going to be instantiating hordes of simple objects. – mgilson May 23 '13 at 19:49